41

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?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Aryan
  • 415
  • 1
  • 4
  • 6

2 Answers2

63

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];
}
erisco
  • 14,154
  • 2
  • 40
  • 45
37

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

}
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111