PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

HOW TO USE switch STATEMENTS IN PHP

There are times when you would want to test many conditions at once and the use of if and elseif statements would make cumbersome, long and confusing code. You can use a switch statement instead which allows you to test a single variable against various conditions (cases) in an easier and efficient way.

The switch statement tests the value of a single variable against various cases you specify and executes a certain block of code when that relevant case is true.

The general format is as follows:

switch ($variableName)

{

case value:

execute code;

break;

case value:

execute code;

break;

default:

execute code;

break;

}

Example:

switch ($myCar)

{

case "BMW":

echo "German Produced";

break;

case "Toyota":

echo "Japanese Produced";

break;

default:

echo "We don't know!";

break;

}

You can have any amount of cases. If the variable $myCar is BMW, then German Produced will be echoed. If the variable $myCar is Toyota, then Japanese Produced will be echoed.

The default part of the switch statement will execute if the variable is none of the cases already specified. For example, If $myCar had a value of Aston Martin, then the default will execute and in our case will echo We don't know!

Note that the break; after each case tells the code to stop executing the switch if it finds the correct case.

Home | Privacy Policy | Terms Of Use | Contact Us