Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - exit from IF block

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...

like image 328
Alex Avatar asked Dec 28 '10 11:12

Alex


People also ask

How do I exit an if statement in PHP?

You can't break if statements, only loops like for or while. If this if is in a function, use 'return'.

How do you exit an IF condition?

The break is a jump statement that can break out of a loop if a specific condition is satisfied. We can use the break statement inside an if statement in a loop. The main purpose of the break statement is to move the control flow of our program outside the current loop.

Can we use break in if php?

The keyword break ends execution of the current for , foreach , while , or do while loops. When the keyword break is executed inside a loop, the control is automatically passed on to the first statement outside of the loop. A break is usually associated with the if statement.

How do you end a loop in PHP?

The PHP break keyword is used to terminate the execution of a loop prematurely. The break statement is situated inside the statement block. It gives you full control and whenever you want to exit from the loop you can come out. After coming out of a loop immediate statement to the loop will be executed.


2 Answers

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.

like image 161
Burak Guzel Avatar answered Sep 29 '22 02:09

Burak Guzel


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

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

like image 30
Oli Avatar answered Sep 29 '22 01:09

Oli