Reputation: 4787
Is it possible ? Or should I end the loop and beginning another ?
foreach($array as $i)
{
if (something)
// Go back
}
Upvotes: 6
Views: 8197
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
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
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
Reputation: 1102
It is not suggested but you can use goto:
cIterator: {
foreach($array as $i)
{
if (something)
goto cIterator;
}
}
Upvotes: 2
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