PHP: How do you determine every Nth iteration of a loop?

后端 未结 8 1238
Happy的楠姐
Happy的楠姐 2020-11-22 13:12

I wanted to echo an image every after 3 post via XML here is my code :



        
相关标签:
8条回答
  • 2020-11-22 13:40

    every 3 posts?

    if($counter % 3 == 0){
        echo IMAGE;
    }
    
    0 讨论(0)
  • 2020-11-22 13:42

    The easiest way is to use the modulus division operator.

    if ($counter % 3 == 0) {
       echo 'image file';
    }
    

    How this works: Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.

    There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.

    0 讨论(0)
  • 2020-11-22 13:44

    How about: if(($counter % $display) == 0)

    0 讨论(0)
  • 2020-11-22 13:52

    Use the modulo arithmetic operation found here in the PHP manual.

    e.g.

    $x = 3;
    
    for($i=0; $i<10; $i++)
    {
        if($i % $x == 0)
        {
            // display image
        }
    }
    

    For a more detailed understanding of modulus calculations, click here.

    0 讨论(0)
  • 2020-11-22 13:52

    It will not work for first position so better solution is :

    if ($counter != 0 && $counter % 3 == 0) {
       echo 'image file';
    }
    

    Check it by yourself. I have tested it for adding class for every 4th element.

    0 讨论(0)
  • 2020-11-22 13:58

    I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.

    if ($ucounter % 1000 == 0) { echo '+'; }
    
    0 讨论(0)
提交回复
热议问题