Any way to break if statement in PHP?

前端 未结 20 1928
無奈伤痛
無奈伤痛 2020-12-02 05:05

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

相关标签:
20条回答
  • 2020-12-02 05:27
    $a = 1;
    
    switch($a) {
    
      case "1":
    
        if  ($condition1){
          break;
        }
    
        if  ($condition2){
          break;
        }
    
        if  ($condition3){
          break;
        }
    }
    

    In this way I got what I want. I use a switch only has a definite case and then use break in case to choose if condition. The reason why I use the break : condition1 and condition2 may both satisfy, in that situation only condition1 is applied .IF is selective according the order.

    0 讨论(0)
  • 2020-12-02 05:29

    The simple answer is that no, there isn't a way to break from an if statement without completely stopping the execution (via exit). Other solutions won't work for me because I can't change the structure of the if statement, since I'm injecting code into a plugin, like so:

    if ( condition ) {
      // Code and variables I want to use
    
      // Code I have control over
    
      // Code I don't want to run
    }
    // More code I want to use
    
    0 讨论(0)
  • 2020-12-02 05:30

    Just move the code that is not supposed to be executed to else/elseif branch. I don't really see why would you want to do what you're trying to do.

    0 讨论(0)
  • 2020-12-02 05:33

    The simple solution is to comment it out.

    $a="test";
    if("test"==$a)
    {
    
      //echo "yes"; //no longer needed - 7/7/2014 - updateded bla bla to do foo
    }
    

    The added benefit is your not changing your original code and you can date it, initial it and put a reason why.

    Why the down vote, according to the OP request I think this is a perfectly valid solution.

    "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?"

    In fact someone could look at some of the other solutions, a year latter and wonder what is going on there. As per my suggestion, one could leave good documentation for future reference, which is always good practice.

    0 讨论(0)
  • 2020-12-02 05:34

    There exist command: goto

    if(smth) {
       .....
       .....
       .....
       .....
       .....
       goto Area1;
       .....
       .....
    
    
    }
    
    
    
    Area1:
    ....your code here....
    

    However, remember goto is not a recommended practice, because it makes the code to be formatted unusually.

    0 讨论(0)
  • 2020-12-02 05:34

    No.

    But how about:

    $a="test";
    if("test"==$a)
    {
      if ($someOtherCondition)
      {
        echo "yes";
      }
    }
    echo "finish";
    
    0 讨论(0)
提交回复
热议问题