有什么办法可以打破 PHP 中的 if 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7468836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:45:10  来源:igfitidea点击:

Any way to break if statement in PHP?

php

提问by Muhammad Usman

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

是否有任何PHP命令停止执行当前或父if陈述,相同breakbreak(1)switch/ loop。例如

$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";

在上面的代码 PHP 不会做echo "test";,会去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 breakthe ifstatement 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?

我想上面breakif语句并停止执行echo "yes";或不再需要执行的此类代码,可能有也可能没有附加条件,有没有办法做到这一点?

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.

更新:发布这个问题仅仅 2 年后,我就长大了,我学会了如何将代码编写成小块,为什么嵌套 if 可能是一种代码异味,以及如何通过编写可管理的小函数首先避免此类问题。

回答by AgelessEssence

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.

不要担心其他用户的评论,我可以理解你,有时在开发这种“花哨”的东西时是必需的。如果我们可以打破一个 if,就不需要很多嵌套的 if,从而使代码更加干净和美观。

This sample code illustratethat 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.

这个示例代码说明了 CERTAINS SITUATIONS where break if 可能比许多丑陋的嵌套if更合适......如果你没有遇到过这种情况并不意味着它不存在

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 gotois an alternative, the bad thing about this is you always need to define the label (point target).

正如@NiematojakTomasz 所说,使用goto是另一种选择,不好的地方是你总是需要定义标签(点目标)。

回答by Maxim Krizhanovsky

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

将您的代码封装在一个函数中。您可以随时停止执行函数return

回答by Rahul Ranjan

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

在阅读了一些评论后,我意识到异常处理对于正常的流控制并不总是有意义的。对于正常的控制流,最好使用“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.

您还可以将进程返回值保存在变量中,然后检查进程失败的失败/异常块。

回答by Markus Zeller

Because you can breakout 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/while 循环,所以让我们“”一轮。最后有一段时间(假),条件永远不会为真,也不会重复。

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

回答by NiematojakTomasz

goto:

转到

The gotooperator 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 gotofollowed 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 gotoin place of a multi-level break...

跳转操作符可以用来跳转到计划中的其他部分。目标点由后跟冒号的标签指定,并且指令为goto后跟所需的目标标签。这不是一个完全不受限制的goto。目标标签必须在同一个文件和上下文中,这意味着你不能跳出一个函数或方法,也不能跳入一个函数或方法。您也无法跳入任何类型的循环或切换结构。您可能会跳出这些,一个常见的用途是使用goto代替多级中断......

回答by T.Todua

There exist command: goto

存在命令: goto

if(smth) {
   .....
   .....
   .....
   .....
   .....
   goto Area1;
   .....
   .....


}



Area1:
....your code here....

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

但是,remembergoto不是推荐的做法,因为它会使代码格式异常。

回答by UltraDEVV

You could use a do-while(false):

您可以使用 do-while(false):

    <?php
    do if ($foo)
    {
      // Do something first...

      // Shall we continue with this block, or exit now?
      if ($abort_if_block) break;

      // Continue doing something...

    } while (false);
    ?>

as described in http://php.net/manual/en/control-structures.if.php#90073

http://php.net/manual/en/control-structures.if.php#90073 中所述

回答by Stphane

No, there is no way to "break" an if block like you would inside loops.:(
So turn your test into a switch!

不,没有办法像在循环中那样“破坏” if 块。:(
所以把你的测试变成一个switch!

I wonder why nobody encouraged you to use switch statementsince(even if you haven't to many test cases)
Do you think it's too verbose?

我想知道为什么没有人鼓励你使用switch 语句,因为(即使你没有很多测试用例)
你认为它太冗长了吗?

I would definitely go for it here

我肯定会去这里

  switch($a){
    case 'test':
        # do stuff here ...
        if(/* Reason why you may break */){
           break; # this will prevent executing "echo 'yes';" statement
        }
        echo 'yes';  # ...           
        break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
    # default:
        # something else here  ..
        # break;
  }

To me Exceptions are meant to raise errors and not really to control execution flaw.
If the break behaviour you are trying to set is not about unexpected error(s), Exception handling is not the right solution here :/.

对我来说,异常意味着引发错误,而不是真正控制执行缺陷。
如果您尝试设置的中断行为与意外错误无关,则异常处理在这里不是正确的解决方案:/

回答by user3530437

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

就这样我得到了我想要的。我使用 switch 只有一个确定的情况,然后使用 break 来选择 if 条件。我使用 break 的原因:condition1 和 condition2 可能都满足,在那种情况下只应用 condition1 .IF 根据顺序是有选择性的。

回答by Mchl

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

只需将不应该执行的代码移动到else/elseif分支即可。我真的不明白你为什么想做你想做的事。