Shealan
Shealan

Reputation: 1346

Print some code from a foreach loop at each predetermined number

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

Upvotes: 1

Views: 979

Answers (3)

user229044
user229044

Reputation: 239382

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 &&...

Upvotes: 1

spinon
spinon

Reputation: 10857

Just write out the logic. It is pretty easy:

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

Upvotes: 0

Luke Stevenson
Luke Stevenson

Reputation: 10351

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

Upvotes: 5

Related Questions