Jayne Herbert
Server Side Programming (PHP) Course
CITN270 – September 2009

Home - assignment 1 - assignment 2


 

 

Code snippts

 

PHP Switch examples

Numeric

This example wil return the default value of "Default - Today's lucky variable value is " and the variable value if anything other than 0, 1, or 2 equeal the variable value.

If the variable value is equal to any of the values contained in the switched values it will return the value set in the case.

$i=7;

switch ($i) {

case 0: echo "Case 0 - Today's lucky variable value is " . "$i" ; break;

case 1: echo "Case 1 - Today's lucky variable value is " . "$i" ; break;

case 2: echo "Case 2 - Today's lucky variable value is " . "$i" ; break;

default: echo "Default - Today's variable value is " . "$i" ; break; }

 

Default - Today's variable value is 7

 

 

In this example it will return "Number 1" as the variable x is set to 1.

$x = 1;

switch ($x) {

case 1: echo "Number 1"; break;

case 2: echo "Number 2"; break;

case 3: echo "Number 3"; break;

default: echo "The variable x is not a number between 1 and 3"; }

 

Number 1

 

Switch example with text

The same idea applies with text but the 'case' value must be in quotation marks.

 

$destination = "Cornwall";

echo "Traveling to $destination";

switch ($destination){

case "Cornwall": echo "Come to " ."$destination" . " and relax" ; break;

case "Amsterdam": echo "Bring an open mind"; break;

case "Egypt": echo "Bring 15 bottles of SPF 50 Sunscreen"; break;

case "Tokyo": echo "Bring lots of money"; break;

case "Caribbean Islands": echo "Bring a swimsuit"; break; }

 

Traveling to Cornwall
Come to Cornwall and relax

 

 

 

 

Note: The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

 

 


 

 

phpcourse.jayne-herbert.co.uk