【问题标题】:Break to Else PHP打破其他 PHP
【发布时间】:2016-04-10 09:21:21
【问题描述】:

所以我有这个代码:

if (isset($_GET['code'])) {
    $code = $_GET['code'];
    if (!array_key_exists($code, $errors)) {
        break 2;  // Move to else to do other stuff
    }
    // Do stuff
} else {
    // Do other stuff
}

但我不能让休息时间去做我想让它做的事情? 我只是得到一个错误:

致命错误:无法在第 161 行的 {filepath}\index.php 中中断/继续 2 个级别 // !array_key_exists 行

那么我怎样才能让 if 中断并转移到 else 上呢?

【问题讨论】:

    标签: php if-statement


    【解决方案1】:

    这是因为break 会破坏forwhile 之类的循环...它不会破坏if...

    您不能从 if 移动到 elseif ;-)

    把它变成这样:

    在友好用户评论后编辑 修复了$code 尚未在if 中分配的错误

    if (isset($_GET['code']) && array_key_exists($_GET['code'], $errors)) {
      $code = $_GET['code'];  
      // Do stuff
    } else {
        do_other_stuff();
    }
    

    【讨论】:

    • 它会显示错误。因为$code已经被初始化成block但是你这里使用了array_key_exists($code, $errors)...
    • @73badf2bb626675fdd519011cbb39e 你完全正确!已编辑。
    【解决方案2】:

    break 语句从最近的封闭loopswitch 语句中分离出来。

    break 不会脱离 if 语句,而是最接近的包含该 if 语句的 loopswitch。不跳出 if 语句的原因是因为它通常用于决定是否要跳出loop

    试试这样:

    if (isset($_GET['code']) && !array_key_exists($_GET['code'], $errors)) {
       // Do some stuff
    else {
        // Do other stuff
    }
    

    【讨论】:

    • 他希望它存在 :-) 所以array_key_exists(),而不是!array_key_exists() :-)
    【解决方案3】:

    试试:

    if (isset($_GET['code']) AND !(array_key_exists($GET['code'],$errors)) {
        $code = $_GET['code'];
    }
    
    elseif (isset($_GET['code']) AND $code = $_GET['code'] AND array_key_exists($code, $errors)) {
        // Do stuff
    }
    
    } else {
        // Do other stuff
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多