|
Free
PHP Tutorials
|
![]() |
home |
Stay
at Home and Learn
|
|||||
PHP Tutorials |
||||||
|
The PHP Switch Statement
In some earlier code, we tested a single variable that came from a drop-down list. A different picture was displayed on screen, depending on the value inside of the variable. A long list of if and else if statements were used. A better option, if you have only one variable to test, is to use something called a switch statement. To see how switch statements work, study the following code: <?php $picture ='church'; switch ($picture)
{ case 'church': ?> In the code above, we place the direct text "church" into the variable called $picture. It's this direct text that we want to check. We want to know what is inside of the variable, so that we can display the correct picture. To test a single variable with a Switch Statement, the following syntax is used: switch ($variable_name) { It looks a bit complex, so we'll break it down. switch ($variable_name) { case 'What_you_want_to_check_for': //code here break;
To see the Switch statement in action, there is a file called "selectPicture2.php" amongst the ones you downloaded (Go here, if you haven't yet downloaded the files for this course). Its in the scripts folder. Try it out, if you like! If you look at the last few lines of the Switch Statement in this file, you'll see something else you can add to your own code: default: The default option is like the else from if else. It's used when there could be other, unknown, options. A sort of "catch all" option.
In the next part, we'll take a look at something called Logial Operators.
<-- Back One Page Move on to the Next Part --> |