Software Development Resources
Log in / create account | Log in with OpenID | Help
DocForge is an open peer-reviewed wiki for software developers. Feel free to edit this page. X

PHP/switch

From DocForge

< PHP

switch-case is a control flow statement which allows a PHP script to make multiple decisions based on a single expression.

[edit] Syntax

switch (<expression>) {
    case <expression>:
        <statements>
        break;
    case <expression>:
        <statements>
        break;
    case <expression>:
    case <expression>:
    case <expression>:
        <statements>
        break;
    default:
        <statements>    
}

Each case expression may be any expression that evaluates to a simple type: numbers and strings. Arrays or objects cannot be used unless they are dereferenced to a simple type.

Each case statement's expression is evaluated until a successful match is found when compared to the switch statement's expression. It's important to note that there is no strict type comparison. Each comparison is the equivalent of the == operator as opposed to the === operator.

The break statement stops the switch statement and continues execution after its block. A case statement not followed by a break will allow execution to continue through the next case or default statement. This is usually referred to as pass-through. This is one of the switch statement's benefits over the if statement in some situations.

Discussion

comments powered by Disqus