phpforeachdo-whilecontinue

Restart foreach loop if condition is satisfied on last iteration


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 doesn't work.


Solution

  • 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:

    $continueLoop = true;
    
    while ($continueLoop) {
        foreach ($getUsers as $index => $user) {
            $userID = saveToDB($user, rand(1,1000));
    
            if ($index == count($getUsers) - 1 && alreadyUsed($userID)) {
                // If you reach the last user and the userID is already used,
                // continue the outer while loop
                continue 2;
            }
        }
    
        // If the end of the foreach loop is reached without restarting,
        // break out of the while loop
        $continueLoop = false;
    }