php – Print some code from a foreach loop at each predetermined number – Education Career Blog

My code is looping through some content and outputting some code.

I need to work out a way of telling my code to output some predefined text every X loops. For example:

Task: print “code here” on loop item 1
and every 4 further loops.

So “code here” will only be outputted on foreach loop item 1, 4, 8, 12

,

$count = 0;
foreach( $yourArray as $oneElement ){
  $count++;
  if( $count==1 || $count%4==0 )
    echo 'code here';
}

,

Assuming you’re using an array with numeric sequential keys, the extra counting variable is not necessary:

foreach($array as $key => $value){
  if ($key == 1 || ($key > 1 && $key % 4 == 0))
    echo 'special string on 1,4,8,12...'; 
  // your code here
}

Note that when you check for every 4th iteration via % 4 you have to make sure you’re not printing on the 0’th element, hence the $key > 1 &&...

,

Just write out the logic. It is pretty easy:

for ($i = 1; $i < 20; $i++)
{
    if ($i == 1 || $i % 4 == 0)
        echo "Print code";
}

Leave a Comment