Home » Php » How to go to next record in foreach loop

How to go to next record in foreach loop

Posted by: admin November 30, 2021 Leave a comment

Questions:

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?

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];
}

###

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];

}