skip to Main Content

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


  1. foreach ($getUsers as $index => $user) {
        $userID = saveToDB($user, rand(1,1000));
        if ($index == count($getUsers) - 1 && alreadyUsed($userID)) {
            continue;
        }
        // Code...
    }
    

    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 🙂

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search