<< PHP If...Else | PHP Tutorials | PHP Arrays >>

PHP Switch

The switch statement is very similar to the if...elseif...else way of doing things. You will have a variable, which you want to find all the possible values that you need. You would use the switch statement to list these possibilities and then do some code or output something if the value is what you want it. Sound hard? Well it isn't - really.

Using the Switch Statement

The first 'layer' of the switch statement is similar to the if statement:

<?php
$variable = 1;
switch ($variable) {

}
?>

The variable has to be ... well a variable :) It can be of any data type you want it to be. Now, you want to find the values of $variable. When using the switch statement These are referred to as cases. Makes sense eh? Now here is an example for you:

<?php
$variable = 1;
switch ($variable) {
    case 1:
    echo 'It is equal to 1';
    break;
}
?>

This is what the end user will see:

It is equal to 1

There are some things you should have noticed above. First of all, I indented some of the code. This is a general thing I like to do when I have nested blocks of code, indent them by 1 tab space. It helps keep code more organized and such. Anyway, another thing you should have noticed is the break; after the echo statement. This tells the PHP parser that you are done processing the code for this case. Any PHP code you want can go between the case ___: and break; statements.

The Default Case

There is also another statement associated with the switch statement. It is the default statement. When using the default statement, if all the conditions in other cases are not met, then this code is executed. Here is an example:

<?php
$variable = 3;
switch ($variable) {
    case 1:
    echo 'It is equal to 1';
    break;
    case 2:
    echo 'It is equal to 2';
    break;
    default:
    echo 'It is not equal to any cases';
    break;
}
?>

This is what the end users will see:

It is not equal to any cases

I changed the value of $variable to 3 for this example. As you can see it is not equal to either 1 or 2, so it uses the default statement to determine what to do. You can also use multiple cases that will execute the same code, with different values. This can be accomplished by dropping the break; statement:

<?php
$variable = 1;
switch ($variable) {
    case 1:
    case 2:
    echo 'It is equal to 1 or 2';
    break;
    default:
    echo 'It is not equal to any cases';
    break;
}
?>

This is what the end users will see:

It is equal to 1 or 2

I changed the value again :P Sorry to have confused you, anyway, not hard eh? Just remember that the break; and case/default statements should be on their own line.

<< PHP If...Else | PHP Tutorials | PHP Arrays >>