Skip to content
Advertisement

Modulus in a PHP loop

I’m currently checking whether an entry in a loop is the third iteration or not, with the following code:

<?php for ($i = 0; $i < count($category_news); $i++) : ?>

    <div class="grid_8">
        <div class="candidate snippet <?php if ($i % 3 == 2) echo "end"; ?>">
            <div class="image shadow_50">
                <img src="<?php echo base_url();?>media/uploads/news/<?php echo  $category_news[$i]['url']; ?>" alt="Image Preview" width="70px" height="70px"/>
            </div>
               <h5><?php echo $category_news[$i]['title']?></h5>
            <p><?php echo strip_tags(word_limiter($category_news[$i]['article'], 15)); ?></p>
            <?php echo anchor('/news/article/id/'.$category_news[$i]['news_id'], '&gt;&gt;', array('class' => 'forward')); ?>
        </div>
    </div>

    <?php if ($i % 3 == 2) : ?>
         </li><li class="row">
    <?php endif; ?>

<?php endfor; ?>

How can I check if the loop is in its second and not its third iteration?

I have tried $i % 2 == 1 to no avail.

Advertisement

Answer

Modulus checks what’s the leftover of a division.

If $i is 10, 10/2 = 5 with no leftover, so $i modulus 2 would be 0.
If $i is 10, 10/3 = 3 with a leftover of 1, so $i modulus 3 would be 1.

To make it easier for you to track the number of item i would start $i from 1 instead of 0. e.g.

for($i=1; $i <= $count; $i++)
    if($i % 2 == 0) echo 'This number is even as it is divisible by 2 with no leftovers! Horray!';
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement