-4

As the title says: I have a foreach loop but every third time the loop will pass it must do something else. How to do this? Thanks in advance. I tried:

$count = 0
foreach ($cObjects as $oObject) {
   if ($count <= 2) {
     //do things
     $count = 0;
   } else {
     // do other things
   }
   $count++;
}

This didn't work ofcourse, while it resets the count everytime to 0.

Replacing if($count <= 2) to if($count == 2) works.

Trekdrop
  • 475
  • 7
  • 27

2 Answers2

3

The answer from Parixit works only on index array, for collection or associative array you will need a separate $count variable, something like this:

$count = 0
foreach ($cObjects as $oObject) {
   if ($count == 2) {
     //do things
     $count = 0;
   } else {
     // do other things
   }
   $count++;
}
William Tran
  • 698
  • 4
  • 7
1

I don't know I understand it proper or not. But you should do something like this

foreach($all as $k=>$single) {
    if($k%3==0) {
        //do every third time
        continue;
    }

    //do something which will not execute every third time
}
Parixit
  • 3,829
  • 3
  • 37
  • 61