Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break out of if and foreach

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach.

foreach ($equipxml as $equip) {      $current_device = $equip->xpath("name");     if ($current_device[0] == $device) {          // Found a match in the file.         $nodeid = $equip->id;          <break out of if and foreach here>     } } 
like image 748
au_stan Avatar asked Feb 09 '12 17:02

au_stan


People also ask

Can you break out of forEach?

Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.

How do you exit a forEach loop if condition is met?

break ends execution of the current for, foreach, while, do-while or switch structure. So yes, you can use it to get out of the foreach loop. Show activity on this post. break statement will break out of the loop.

Can we use forEach in if condition?

You can use if condition in foreach loop in laravel using @if directive in laravel blade. You can also use if statement in laravel controller as php if statement.

How do you end a forEach loop?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.


2 Answers

if is not a loop structure, so you cannot "break out of it".

You can, however, break out of the foreach by simply calling break. In your example it has the desired effect:

$device = "wanted"; foreach($equipxml as $equip) {     $current_device = $equip->xpath("name");     if ( $current_device[0] == $device ) {         // found a match in the file                     $nodeid = $equip->id;          // will leave the foreach loop and also the if statement         break;         some_function(); // never reached!     }     another_function();  // not executed after match/break } 

Just for completeness for others that stumble upon this question looking for an answer..

break takes an optional argument, which defines how many loop structures it should break. Example:

foreach (array('1','2','3') as $a) {     echo "$a ";     foreach (array('3','2','1') as $b) {         echo "$b ";         if ($a == $b) {              break 2;  // this will break both foreach loops         }     }     echo ". ";  // never reached! } echo "!"; 

Resulting output:

1 3 2 1 !

like image 82
Kaii Avatar answered Oct 16 '22 02:10

Kaii


foreach($equipxml as $equip) {     $current_device = $equip->xpath("name");     if ( $current_device[0] == $device ) {         // found a match in the file                     $nodeid = $equip->id;         break;     } } 

Simply use break. That will do it.

like image 20
Decent Dabbler Avatar answered Oct 16 '22 01:10

Decent Dabbler