Matt Cowley
Matt Cowley

Reputation: 2373

Break to Else PHP

So I have this code:

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
}

But I can't get the break to do what I want it to do? I just get an error:

Fatal error: Cannot break/continue 2 levels in {filepath}\index.php on line 161 // Line of the !array_key_exists

So how can I get the if to break and move onto the else?

Upvotes: 0

Views: 146

Answers (3)

Flash Thunder
Flash Thunder

Reputation: 12045

This is because break breaks loops like for or while ... it won't break if...

You can't move from if to else of that if ;-)

make it like this:

EDIT AFTER COMMENT OF FRIENDLY USER Fixed error with $code not assigned yet in if

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

Upvotes: 3

Try:

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
}

Upvotes: 0

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

The break statement breaks out of the nearest enclosing loop or switch statement.

break does not break out of an if statement, but the nearest loop or switch that contains that if statement. The reason for not breaking out of an if statement is because it is commonly used to decide whether you want to break out of the loop.

Try like this:

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

Upvotes: 2

Related Questions