Zooly
Zooly

Reputation: 4787

Go back at the beginning of a foreach loop in PHP

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

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

Upvotes: 6

Views: 8197

Answers (5)

Ryan
Ryan

Reputation: 195

Use continue

From the PHP docs: continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

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

Upvotes: -1

Ulver
Ulver

Reputation: 905

You can use current(), next() and prev() to loop through 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);
    }
}

Upvotes: 1

Alex M
Alex M

Reputation: 514

It is. But not with foreach & without leaving 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]);
}

Upvotes: 5

Good Luck
Good Luck

Reputation: 1102

It is not suggested but you can use goto:

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

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

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

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

Upvotes: 1

Related Questions