Switch statement

The switch statement is basically a replacement for a number of if statements. The structure takes a single variable and then compares it against a number of cases. If the variables matches the case, some PHP code is executed just like an if statement.

The basics

Suppose you wanted to output the cost of a selected product, you may have used if statements to get the following code:

<?php
$product 
'Computer';  /* just an example */

if($product == 'Computer')
{
    
$cost '£400.00';
} elseif(
$product == 'XBOX') {
    
$cost '£130.00';
} elseif(
$product == 'DVD') {
    
$cost '£11.00';
}
echo 
$cost/* will output £400.00 */
?>

This however can easily be replaced using a switch:

<?php
$product 
'Computer';  /* just an example */

switch($product)
{
    case 
'Computer':
        
$cost '£400.00';
    break;

    case 
'XBOX':
        
$cost '£130.00';
    break;

    case 
'DVD':
        
$cost '£11.00';
    break;
}
echo 
$cost/* will output £400.00 */
?>

Let's take a look at the above code: we wrap the variable we want to use in brackets and then use curly brackets to open the switch just like an if statement.


For every comparison we want to make we use the case keyword along with the value we want to check the variable is equal to in quotes, we then add a colon followed by the PHP code we want to execute if the expression is true. Finally a break is added, this exits the switch and prevents further cases being executed. More about breaks and continues.

Multiple cases

You may want to execute the same code for multiple cases, this can be done by simply 'stacking' the cases:

<?php
$product 
'CD';  /* just an example */

switch($product)
{
    case 
'Computer':
        
$cost '£400.00';
    break;

    case 
'XBOX':
        
$cost '£130.00';
    break;

    case 
'DVDR':
    case 
'CD':
    case 
'DVD':
        
$cost '£11.00';
    break;
}
echo 
$cost/* will output £11.00 */
?>

And it's as easy as that!

The default case

If we take the above example - what would happen if $product didn't match any of the cases? There would be no output. This can be solved by using a special 'default' case:

<?php
$product 
'Television';  /* just an example */

switch($product)
{
    case 
'Computer':
        
$cost '£400.00';
    break;

    case 
'XBOX':
        
$cost '£130.00';
    break;

    case 
'DVDR':
    case 
'CD':
    case 
'DVD':
        
$cost '£11.00';
    break;

    default:
        
$cost '£0.00';
    break;
}
echo 
$cost/* will output £0.00 */
?>

The default case will be executed when the variable does not match any of the others.


And that is PHP switch statements in a nutshell!