PHP - exit from IF block

90,097

Solution 1

Why not just turn it around.

if($bla): 
  $bla = get_bla();
  if(!empty($bla)) {
    do($bla);
  }
endif;

That way it will only run your code if $bla isn't empty.. That's kinda the point with if-statements

Solution 2

In PHP 5.3 you can use goto

if($bla): 
   $bla = get_bla();
   if(empty($bla)) goto end;
   do($bla);
endif;
end:

But personally I think that's an ugly solution.

Solution 3

You can't break if statements, only loops like for or while.

If this if is in a function, use 'return'.

Solution 4

Try this

do {

    if($bla) {
        $bla = get_bla();

        if (empty($bla)) {
            break;
        }

        do($bla);
    }

    /* You can do more comparisions here */

} while (0);

Solution 5

I cant believe no one have post this solution yet (writing it in my PHP style):

if($bla){do{
  $bla = get_bla();
  if(empty($bla)) break;
  do($bla);
}while(false);}

Complexity still O(1)

Share:
90,097
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on March 25, 2021

Comments

  • Alex
    Alex about 3 years

    How can I exit a if block if a certain condition is met?

    I tried using break but it doesn't work:

    if($bla): 
      $bla = get_bla();
      if(empty($bla)) break;
      do($bla);
    endif;
    

    it says: Fatal error: Cannot break/continue 1 level in...