Foreach, with variation every X

5 posts by 2 authors in: Forums > CMS Builder
Last Post: December 15, 2008   (RSS)

Re: [rjbathgate] Foreach, with variation every X

By Dave - November 17, 2008

Hi Rob,

Yes, there's a modulus operator that does that. http://www.php.net/manual/en/language.operators.arithmetic.php

So, $a % $b gives you the remainder of $a divided by $b. So if you have a counter you can test if it cleanly divides into 3 like this:

if (($counter % 3) == 0) { ...

Or, if the remainder of your counter divided by 3 is zero.

Or, in one line:

<?php foreach ... ?>
<?php $isThird = @++$myCounter % 3 == 0; ?>
<?php
if ($isThird) { $class = "bucket"; }
else { $class = "bucketThird"; }
?>

or

<?php if ($isThird): ?> ... <?php endif ?>

Sometimes it's easier (simpler to understand) to just have a counter and reset it when it gets to 3, but both would work:

$counter = 0;
foreach ...
$counter++;

if ($counter == 3) {
$counter = 0;
print "3rd row";
}

Let me know if one of those solutions works for you.
Dave Edis - Senior Developer
interactivetools.com

Re: [Dave] Foreach, with variation every X

By rjbathgate - November 17, 2008 - edited: November 17, 2008

Cheers Dave,

It's for something we'll be integrating in the near future so I'll reply here with what worked for me, when we do it...

It will be very handy when having divs displaying horizontally, to be able to give the last div on each line a different class style (e.g. when each div has right margin, the last one on each line needs no right margin in order to main symmetry with the main template).

Cheers again
Rob

Re: [rjbathgate] Foreach, with variation every X

Hi again,

Just an update on what worked for me:

<?php $counter = 1; ?>
<?php foreach ($productsRecords as $record): ?>

<?php if ($counter <> 4): ?>
<p>Normal</p>
<?php endif ?>

<?php if ($counter == 4): ?>
<p>This is forth</p>
<?php $counter = 0; ?>
<?php endif ?>

<?php $counter++; ?>
<?php endforeach; ?>


Many thanks Dave
Rob

Re: [rjbathgate] Foreach, with variation every X

By Dave - December 15, 2008

Glad it's working. Thanks for sharing your code! :)
Dave Edis - Senior Developer
interactivetools.com