Go back to the beginning of the foreach loop in PHP

Is it possible? Or should I end the loop and start another?

foreach($array as $i)
{
    if (something)
        // Go back
}

      

+3


source to share


5 answers


It. But not with foreach or exiting the loop. Here's another alternative, for good measure.



for ($i = 0; $i < count($array); $i++) {
  if (condition) {
    $i = 0;
  }
  do_stuff_with($array[$i]);
}

      

+1


source


Create a function and pass an array. If something happens in the loop, call the function again with the main array. Try it -



function check_loop($array) {
   foreach($array as $val) {
      if (something)
         check_loop($array);
   }
}
check_loop($array);

      

+1


source


Not recommended, but you can use goto:

cIterator: { 
foreach($array as $i)
{
    if (something)
        goto cIterator; 
}
}

      

+1


source


You can use the current (), next (), and prev () functions to cycle through the array and move the internal array pointer back and forth:

$items = array("apple", "box", "cat");
while($item=current($items)) {
    print_r($item);
    if (needToGoBack($item))
        // Go to previous array item
        $item = reset($items);
    } else {
        // Continue to next
        $item = next($items);
    }
}

      

+1


source


Use continuation

From the PHP docs: continue is used in loop structures to skip the rest of the current loop iteration and continue execution when evaluating the state, and then at the start of the next iteration.

http://php.net/manual/en/control-structures.continue.php

0


source







All Articles