PHP - English

PHP Switch Statements



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:


$picture =’church’;

switch ($picture) {

case ‘kitten’:

print(‘Kitten Picture’);

case ‘church’:

print(‘Church Picture’);



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

switch ($variable_name) {

case ‘What_you_want_to_check_for’:

//code here


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 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!

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:

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”


In the next part, we’ll take a look at something called Logial Operators.


Kaynak : ‘sitesinden alıntı

Yorum Yap