Quakenet/#php Tutorial

Note: If you opened this page from an external URL pay attention that all chapters are linked together. Be sure you also read all prior chapters of this tutorial, otherwise you will miss relevant content explained before.

Switch statements

  1. Switch statements

1. Switch statements

A switch statement is a special control structure. Instead of checking any condition or expression like an if statement a switch statement can only be used to compare a expression agains a list of other expressions. It uses internally the compare operator ==.

Such a switch statement can be create with the keyword switch. It is followed by an expression written in parentheses, typically a variable. After that the body of the switch statement is followed, which starts and ends with curly brackets ({ and }).

<?php
switch ($var) {
}
?>

Inside of the switch body you can add case lines. The php interpreter jumps to this line if the expression has the same value as the value behind the case keyword. After the case expression there must be placed a colon :.

<?php
switch ($var) {
case 
5:   // jump here if 5 == $var
case "b"// jump here if "b" == $var
}
?>

This is like a goto command, however such a command dont exists in php. If php jumps to a case block he executes the php code standing there. If he find any other case lines php ignores them. This also means the block doesn't stop at the next case.

<?php
$var 
4;
switch (
$var) {
case 
0:
    echo 
"I am not executed";
case 
4:
    echo 
"I get executed";
case 
90:
    echo 
"But I get executed, too";
}
?>

If you dont want this add a break statement. This will quit the case part and jumps to the end of the switch statement.

<?php
$var 
4;
switch (
$var) {
case 
0:
    echo 
"I am not executed";
    break;
case 
4:
    echo 
"I get executed";
    break;
case 
90:
    break; 
// useless as you are already at the end
}
?>

If there is no matching case php jumps to the default: line, if there is one.

<?php
switch ($formaction) {
case 
'delete':
    echo 
"Something gets deleted";
    break;
case 
'save':
    echo 
"Something gets saved";
    break;
default:
    echo 
"Show something or do something if no case is matched";
    break;
case 
'reload'// can be found and is NOT catched by the default line 
    
echo "Something gets reloaded";
    break;
}
?>

It is possible to add a default: line everywhere but such a block should be only placed as the last of all case blocks. This will increased the readability of your scripts. First an expression is checked again every case line and if no case line is found the default: line is loaded. Its like an else part of an if statement.

Questions about the chapter

No questions

Back to Next to
Copyright © to the OPs of #php/QuakeNet Valid XHTML 1.0 Strict Valid CSS!