By using this site you agree to the use of cookies and related technologies.

Learn more

PHP Switch Statements

PHP Switch Statement Tutorial. Learn how to work with Switch statements in PHP, and about using Switch vs If Statements.

Edited: 2016-09-24 01:22

Another useful way to make simple comparison, and display different information depending on the circumstances, is using PHP Switch Statements.

The PHP Switch is similar to a series of PHP IF statements.

PHP Switch Example

The below will execute some conditional based code, relying on the value of the $i variable.

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}

And now, using strings with the PHP Switch:

switch ($input) {
    case "Brugbart":
        echo "Brugbart Is cool!";
        break;
    case "Rocking":
        echo "Brugbart Rocks!";
        break;
    case "Beaf":
        echo "Brugbart is totally beaf!";
        break;
}

How it works

The switch is read one line at a time, and stops executing when a case matches the input, in this example the $input variable.

Its important that you don't forget to include a break; Otherwise php executes the code inside the exceeding statements. You may however intentionally chose to leave out the break;, which is fine in cases where you would want this to happen.

switch ($input) {
    case "Frontpage":
        include 'Frontpage.php';
        break;
    case "Rocking":
        echo "Brugbart Rocks!"; // Will not get executed if Beaf
    case "Beaf":
        echo "And Brugbart is totally beaf!"; // Gets executed if Rocking
        break;
}

PHP Switch vs If statements

Its pretty much down to personal preference, and while there might be a slight performance difference, its not of any significance. Some sources claim the switch statement's to be faster, while other sources claim that if statement's are faster. it should be mentioned that the difference quoted would be in the 0.0x magnitude.

For most developers, its more a question about personal preference. So you are generally free to chose how you want to code.