jzvelc
jzvelc

Reputation: 207

If() vs. switch() - Same meaning but different behaviour?

I would like to transform my if() conditional to switch() from this:

if($configuration['application'][$applicationName]['subdomain'] == true){
    foreach($configuration['language'] as $language){
        if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
            $_SESSION['language'] = $language['abbreviation'];
        }
    }

    // If no subdomain detected and redirection is enabled, set default language
    if(!isset($_SESSION['language'])){
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
    }
}
else {
    $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
}

To this:

switch($configuration['application'][$applicationName]['subdomain']){
    case true:
        foreach($configuration['language'] as $language){
            if($language['abbreviation'].'.'.$configuration['application'][$applicationName]['domain'] == $_SERVER['HTTP_HOST']){
                $_SESSION['language'] = $language['abbreviation'];
                break;
            }
        }
    default:
        $_SESSION['language'] = $configuration['application'][$applicationName]['language'];
        break;
}

I think it should be the same but it behaves differently ... Switch is not working properly ...

Upvotes: 1

Views: 265

Answers (1)

slugster
slugster

Reputation: 49974

I have reformatted your code, please check to make sure it is still correct.

As for your problem, to begin with you are missing a break; statement at the end of your case true: statement. (The break inside the foreach loop simply breaks out of that loop, not the case itself).

Upvotes: 1

Related Questions