Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go to next record in foreach loop

In the following code, if $getd[0] is empty, I want to go to the next record.

foreach ($arr as $a1) {   $getd = explode(',' ,$a1);   $b1 = $getd[0]; } 

How can I achieve it?

like image 203
Aryan Avatar asked Apr 17 '11 03:04

Aryan


People also ask

How do you go to next in forEach?

The reason why using a return statement to continue in a JavaScript forEach loop works is because when you use a forEach loop you have to pass in a callback function. The only way to continue to the next iteration is when your callback function completes and finishes running the code within itself.

How do you continue a forEach loop?

In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop. Basically, it skips its given statements and continues with the next iteration of the loop.

Can we use continue and break statements with the forEach loop?

No, it doesn't, because you pass a callback as a return, which is executed as an ordinary function. All forEach does is call a real, actual function you give to it repeatedly, ignore how it exits, then calls it again on the next element.


2 Answers

We can use an if statement to only cause something to happen if $getd[0] is not empty.

foreach ($arr as $a1) {     $getd=explode(",",$a1);     if (!empty($getd[0])) {         $b1=$getd[0];     } } 

Alternatively, we can use the continue keyword to skip to the next iteration if $getd[0] is empty.

foreach ($arr as $a1) {     $getd=explode(",",$a1);     if (empty($getd[0])) {         continue;     }     $b1=$getd[0]; } 
like image 173
erisco Avatar answered Sep 29 '22 19:09

erisco


Using continue which will skip to the next iteration of the loop.

foreach ($arr as $a1){     $getd=explode(",",$a1);       if(empty($getd[0])){         continue;     }      $b1=$getd[0];  } 
like image 38
Mike Lewis Avatar answered Sep 29 '22 18:09

Mike Lewis