php modulus in a loop

陌路散爱 提交于 2019-11-27 02:08:35

Modulus checks whats 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!';

Hope its understandable. Shai.

When in doubt, write a snippet of code:

for ($j = 1; $j < 4; $j++)
{
   for ($k = 0; $k < $j; $k++)
   {
      echo "\n\$i % $j == $k: \n";

      for ($i = 0; $i < 10; $i++)
      {
         echo "$i : ";
         if ($i % $j == $k)
         {
            echo "TRUE";
         }
         echo " \n";
      }
   }
}

Here is the output. Use it to figure out what you need to use:

$i % 1 == 0: 
0 : TRUE 
1 : TRUE 
2 : TRUE 
3 : TRUE 
4 : TRUE 
5 : TRUE 
6 : TRUE 
7 : TRUE 
8 : TRUE 
9 : TRUE 

$i % 2 == 0: 
0 : TRUE 
1 :  
2 : TRUE 
3 :  
4 : TRUE 
5 :  
6 : TRUE 
7 :  
8 : TRUE 
9 :  

$i % 2 == 1: 
0 :  
1 : TRUE 
2 :  
3 : TRUE 
4 :  
5 : TRUE 
6 :  
7 : TRUE 
8 :  
9 : TRUE 

$i % 3 == 0: 
0 : TRUE 
1 :  
2 :  
3 : TRUE 
4 :  
5 :  
6 : TRUE 
7 :  
8 :  
9 : TRUE 

$i % 3 == 1: 
0 :  
1 : TRUE 
2 :  
3 :  
4 : TRUE 
5 :  
6 :  
7 : TRUE 
8 :  
9 :  

$i % 3 == 2: 
0 :  
1 :  
2 : TRUE 
3 :  
4 :  
5 : TRUE 
6 :  
7 :  
8 : TRUE 
9 :  

Now for the answer:

How can I check the loop is on it's 2nd interation not it's 3rd I have tried,

$i % 2 === 0

for every third iteration you need

if ($i % 3 === 0) 

if particular third iteration then

if ($i === 3)   

I think it should be:

if ($i % 2 == 0) 

Try this, should work for every 3rd iteration:

if ($i % 3 === 0) 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!