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

后端 未结 8 1239
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:59

    Going off of @Powerlord's answer,

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

    You can still start your counter at 0 (arrays, querys), but offset it

    if (($counter + 1) % 3 == 0) {
      echo 'image file';
    }
    
    0 讨论(0)
  • 2020-11-22 14:02

    You can also do it without modulus. Just reset your counter when it matches.

    if($counter == 2) { // matches every 3 iterations
       echo 'image-file';
       $counter = 0; 
    }
    
    0 讨论(0)
提交回复
热议问题