Friday, 24 August 2012

PHP Tutorial Lesson #8 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 'kitten':
print('Kitten Picture');
break;

case 'church':
print('Church Picture');
break;
}

?>

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) {
case 'What_you_want_to_check_for':
//code here
break;
}

It looks a bit complex, so we'll break it down.

switch ($variable_name) {
You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you type the name of the variable you want to check. After the round brackets, you need a left curly bracket.

case 'What_you_want_to_check_for':
The word 'case' is used before each value you want to check for. In our code, a list of values was coming from a drop-down list. These value were: church and kitten, among others. These are the values we need after the word 'case'. After the the text or variable you want to check for, a colon is needed ( : ).

//code here
After the semi colon on the 'case' line, you type the code you want to execute. Needless to say, you'll get an error if you miss out any semi-colons at the end of your lines of code!

break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop down to the next case and check that. Use the word 'break' to get out of the Switch statement.



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:
print ("No Image Selected");

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.

0 comments:

Post a Comment