23

I am getting sometimes this error on production at:

if( true == $objWebsite ) {
    $arrobjProperties = (array) $objWebsite->fetchProperties( );
    if( false == array_key_exists( $Id, $Properties ) ) {
       break;
    }
    $strBaseName = $strPortalSuffix . '/';

    return $strBaseName;
}

$strBaseName = $strSuffix ;
return $strBaseName;

I have tried to reproduce this issue. But not getting any progress. $Id, $Properties having value received.

Does anyone know when does 'Cannot break/continue 1 level' comes in PHP?

I have seen this post PHP Fatal error: Cannot break/continue. But didn't got any help.

Community
  • 1
  • 1
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226

3 Answers3

34

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';
?>
Robbie
  • 17,605
  • 4
  • 35
  • 72
2

If within a function just change break; to return;

SudarP
  • 906
  • 10
  • 12
  • 2
    Why return? If there are 0 statements to execute after `if` then we can return. But if some statements need to execute then we should not return. – Somnath Muluk Jan 15 '16 at 09:52
  • 1
    I agree in that case. It also depends what logic that code block is trying to apply. Ya so not always return. – SudarP Jan 28 '16 at 01:56
1

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++;
}
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226