Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to break if statement in PHP?

Tags:

php

Is there any command in PHP to stop executing the current or parent if statement, same as break or break(1) for switch/loop. For example

$arr=array('a','b');
foreach($arr as $val)
{
  break;
  echo "test";
}

echo "finish";

in the above code PHP will not do echo "test"; and will go to echo "finish";

I need this for if

$a="test";
if("test"==$a)
{
  break;
  echo "yes"; // I don't want this line or lines after to be executed, without using another if
}
echo "finish";

I want to break the if statement above and stop executing echo "yes"; or such codes which are no longer necessary to be executed, there may be or may not be an additional condition, is there way to do this?

Update: Just 2 years after posting this question, I grew up, I learnt how code can be written in small chunks, why nested if's can be a code smell and how to avoid such problems in the first place by writing manageable, small functions.

like image 434
Muhammad Usman Avatar asked Sep 19 '11 09:09

Muhammad Usman


People also ask

Can I use break in if statement 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.

Can you break out of an if statement?

You can't break out of if statement until the if is inside a loop. The behaviour of the break statement is well specified and, generally, well understood. An inexperienced coder may cause crashes though a lack of understanding in many ways. Misuse of the break statement isn't special.

How do you jump out of if condition?

You can't break out of an if block. There has to be a reason why you'd want to break out there otherwise you'd just remove echo two and be done with it. That being the case, just enclose the rest of the code in another condition so that it only executes when you want it to.

How do you stop a loop when a condition is met PHP?

Using break keyword: The break keyword is used to immediately terminate the loop and the program control resumes at the next statement following the loop. To terminate the control from any loop we need to use break keyword.


5 Answers

Sometimes, when developing these "fancy" things are required. If we can break an if, a lot of nested ifs won't be necessary, making the code much more clean and aesthetic.

This sample code illustrates that in certain situations a breaked if can be much more suitable than a lot of ugly nested ifs.

Ugly code

if(process_x()) {

    /* do a lot of other things */

    if(process_y()) {

         /* do a lot of other things */

         if(process_z()) {

              /* do a lot of other things */
              /* SUCCESS */

         }
         else {

              clean_all_processes();

         }

    }
    else {

         clean_all_processes();

    }

}
else {

    clean_all_processes();

}

Good looking code

do {
  
  if( !process_x() )
    { clean_all_processes();  break; }
  
  /* do a lot of other things */
  
  if( !process_y() )
    { clean_all_processes();  break; }
  
  /* do a lot of other things */
  
  if( !process_z() )
    { clean_all_processes();  break; }
  
  /* do a lot of other things */
  /* SUCCESS */
  
} while (0);

As @NiematojakTomasz says, the use of goto is an alternative, the bad thing about this is you always need to define the label (point target).

like image 87
AgelessEssence Avatar answered Oct 22 '22 08:10

AgelessEssence


Encapsulate your code in a function. You can stop executing a function with return at any time.

like image 34
Maxim Krizhanovsky Avatar answered Oct 22 '22 07:10

Maxim Krizhanovsky


proper way to do this :

try{
    if( !process_x() ){
        throw new Exception('process_x failed');
    }

    /* do a lot of other things */

    if( !process_y() ){
        throw new Exception('process_y failed');
    }

    /* do a lot of other things */

    if( !process_z() ){
        throw new Exception('process_z failed');
    }

    /* do a lot of other things */
    /* SUCCESS */
}catch(Exception $ex){
    clean_all_processes();
}

After reading some of the comments, I realized that exception handling doesn't always makes sense for normal flow control. For normal control flow it is better to use "If else":

try{
  if( process_x() && process_y() && process_z() ) {
    // all processes successful
    // do something
  } else {
    //one of the processes failed
    clean_all_processes();
  }
}catch(Exception ex){
  // one of the processes raised an exception
  clean_all_processes();
}

You can also save the process return values in variables and then check in the failure/exception blocks which process has failed.

like image 44
Rahul Ranjan Avatar answered Oct 22 '22 06:10

Rahul Ranjan


Because you can break out of a do/while loop, let us "do" one round. With a while(false) at the end, the condition is never true and will not repeat, again.

do
{
    $subjectText = trim(filter_input(INPUT_POST, 'subject'));
    if(!$subjectText)
    {
        $smallInfo = 'Please give a subject.';
        break;
    }

    $messageText = trim(filter_input(INPUT_POST, 'message'));
    if(!$messageText)
    {
        $smallInfo = 'Please supply a message.';
        break;
    }
} while(false);
like image 28
Markus Zeller Avatar answered Oct 22 '22 06:10

Markus Zeller


goto:

The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label. This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break...

like image 19
NiematojakTomasz Avatar answered Oct 22 '22 06:10

NiematojakTomasz