PHP循环中的模量 [英] Modulus in a PHP loop

查看:80
本文介绍了PHP循环中的模量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下代码检查循环中的条目是否是第三次迭代:

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 % 2 == 1无济于事.

推荐答案

Modulus检查除法的剩余部分.

Modulus checks what's the leftover of a division.

如果$ i为10,则10/2 = 5,没有剩余,因此$ i模数2将为0.
如果$ i为10,则10/3 = 3,剩余值为1,因此$ i模数3将为1.

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.

要使您更容易跟踪i的项目数,可以将$ i从1而不是0开始.例如

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!';

这篇关于PHP循环中的模量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆