-2

Php 'Continue' will tell it to skip the current iteration block, but continue on with the rest of the loop. Works in all scenerios (for, while, etc.).But I want to skip the rest of the loop.I tried it using break;But not work.

if ($column_names > 0) {
    foreach ($column_names as $heading) {
        foreach ($heading as $column_heading)
            if($column_heading == "trip_id"){
                break;
            }
            if($column_heading == "number_of_pessengers"){
                $column_heading = "No. pessengers";
            }
            $cellWidth = $pdf->GetStringWidth($column_heading);
            $pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
    }
}

What's the wrong in my code.

Jayani Sumudini
  • 1,409
  • 2
  • 22
  • 29

2 Answers2

5

Try break 2;

If you want to exit out of nested loops you have to use the "argument" for break.

foreach ($column_names as $heading) {
    foreach ($heading as $column_heading)
        if($column_heading == "trip_id"){
            break 2; //break out of both loops.
        }
        if($column_heading == "number_of_pessengers"){
            $column_heading = "No. pessengers";
        }
        $cellWidth = $pdf->GetStringWidth($column_heading);
        $pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
     }
}

Who knew you can put a number with break, also continue works the same way.

http://php.net/manual/en/control-structures.break.php

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

Cheers

Community
  • 1
  • 1
ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
-1

If you want to exist from both loop then you have to keep a flag variable

if ($column_names > 0) {
foreach ($column_names as $heading) {
  $flag = 0;
    foreach ($heading as $column_heading){
        if($column_heading == "trip_id"){
            $flag = 1;
            break;
        }
        if($column_heading == "number_of_pessengers"){
            $column_heading = "No. pessengers";
        }
        $cellWidth = $pdf->GetStringWidth($column_heading);
        $pdf->Cell($cellWidth + 2, 10, $column_heading, 1);
     }
   if($flag == 1) break;
}

or you can use break 2;

you can check here How can I break an outer loop with PHP?

Anshul
  • 464
  • 4
  • 14