Monday, January 7, 2008

The PHP Switch Statement


$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.



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). It’s 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:
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.

No comments: