Any way to break if statement in PHP?

前端 未结 20 2020
無奈伤痛
無奈伤痛 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:12

    Don't worry about other users comments, I can understand you, SOMETIMES when developing this "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 illustrate that CERTAINS SITUATIONS where breaked if can be much more suitable than a lot of ugly nested ifs... if you haven't faced that certain situation does not mean it doesn't exists.

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

提交回复
热议问题