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

后端 未结 8 1320
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: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.

提交回复
热议问题