How do I restart a foreach loop when I reach the last index and some other condition?
The loop needs to run again, instead, it just stops.
foreach ($getUsers as $index => $user) {
$userID = saveToDB($user, rand(1,1000));
if($index == count($getUsers) && alreadyUsed($userID)) {
reset($getUser);
reset($index);
}
}
This doesnt work
2
Answers
When the condition is met, the loop will skip the rest of the current iteration and start from the next iteration, thus restarting the loop.
Sorry google translate 🙂
The reset() function in PHP is used to reset the internal pointer of an array to its first element, but it doesn’t impact the control flow of a foreach loop, you could achieve desired behaviour, like this: