Why does 'Cannot break/continue 1 level' comes in PHP?

安稳与你 提交于 2019-12-03 22:22:04

You can't "break" from an if statement. You can only break from a loop.

If you want to use it to break from a loop in a calling function, you need to handle this by return value - or throw an exception.


Return value method:

while (MyLoop) {
   $strSecureBaseName = mySubFunction();
   if ($strSecureBaseName === false) {   // Note the triple equals sign.
        break;
   }
   // Use $strSecureBaseName;
}

// Function mySubFunction() returns the name, or false if not found.

Using exceptions - beautiful example here: http://php.net/manual/en/language.exceptions.php

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
        else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

If within a function just change break; to return;

If you want to still break from if, you can use while(true)

Ex.

$count = 0;
if($a==$b){
    while(true){
        if($b==$c){
            $count = $count + 3;
            break;  // By this break you will be going out of while loop and execute remaining code of $count++.
        }
        $count = $count + 5;  //
        break;  
    }
    $count++;
}

Also you can use switch and default.

$count = 0;
if($a==$b){
    switch(true){
      default:  
         if($b==$c){
            $count = $count + 3;
            break;  // By this break you will be going out of switch and execute remaining code of $count++.  
        }
        $count = $count + 5;  //
    }
    $count++;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!