Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you 'exit' a loop in PHP?

Tags:

loops

php

People also ask

How do I exit a loop?

The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .

Can we use break in if PHP?

The keyword break ends execution of the current for , foreach , while , or do while loops. When the keyword break is executed inside a loop, the control is automatically passed on to the first statement outside of the loop. A break is usually associated with the if statement.

Does Return break while loop PHP?

PHP 7 requires a return . A break; is not needed because the loop ends on return . A break; is usually used in a switch or loop whenever you have found your needed item.

How do you end a while in PHP?

The keyword break ends execution of the current for, foreach, while, do while or switch structure. When the keyword break executed inside a loop the control automatically passes to the first statement outside the loop.


You are looking for the break statement.

$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
    if ($val == 'stop') {
        break;    /* You could also write 'break 1;' here. */
    }
    echo "$val<br />\n";
}

As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.

For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.

$person = "Rasmus Lerdorf";
$found = false;

foreach($organization as $oKey=>$department)
{
   foreach($department as $dKey=>$group)
   {
      foreach($group as $gKey=>$employee)
      {
         if ($employee['fullname'] == $person)
         {
            $found = true;
            break 3;
         }
      } // group
   } // department
} // organization

break; leaves your loop.

continue; skips any code for the remainder of that loop and goes on to the next loop, so long as the condition is still true.


You can use the break keyword.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!