kwek-kwek kwek-kwek - 8 months ago 77
PHP Question

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

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

// URL of the XML feed.
$feed = 'test.xml';
// How many items do we want to display?
//$display = 3;
// Check our XML file exists
if(!file_exists($feed)) {
die('The XML file could not be found!');
// First, open the XML file.
$xml = simplexml_load_file($feed);
// Set the counter for counting how many items we've displayed.
$counter = 0;
// Start the loop to display each item.
foreach($xml->post as $post) {
echo '
<div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>

// Increase the counter by one.
// Check to display all the items we want to.
if($counter >= 3) {
echo 'image file';
//if($counter == $display) {
// Yes. End the loop.
// break;
// No. Continue.

here is a sample first 3 are correct but now it doesn't loop


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.