Get latest news and Web Designing tutoria

Friday, 29 May 2015

PHP Switch Statements

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.

0 comments:

Post a Comment