Switch Statements

//Gift certificates are given in denominations of
//100, 200, 300, 400, or 500
//Based on the of the certificate you are
//going shopping and/or out with your honey.

//set the variable to 500
$giftdollars=500;

switch ($giftdollars)
{
case 100:
print("I can buy shoes!");
break;

case 200:
print("I can buy shoes and an outfit!");
break;

case 300:
print("I can buy shoes, an outfit, and tickets to a play!");
break;

case 400:
print("Ican buy shoes, an outfit, tickets to a play, and a weekend getaway!");
break;

default:
print("I'm buying an X-Box 360!");
}

The above code evaluates each case, and runs the subsequent block of code. The break statement steps out of the switch statement and the default provides the code to run when no case is a match. .

Here's an example:switch.php


<html>
<head>
<title>switch.php</title>
</head>
<body>

<?php
//Gift certificates are given in denominations of
//50, 100, 200, 300, 400, 500, or 1000
//Based on the of the certificate you are
//going shopping and/or out with your honey.

//set the variable to 500
$giftdollars=500;

switch (
$giftdollars)
    {
        case 
50:  //case 50 and case 100 will produce the same result.
        
case 100
            print(
"I can buy shoes!");
            break;

        case 
200
            print(
"I can buy shoes and an outfit!");
            break;

        case 
300
            print(
"I can buy shoes, an outfit, and tickets to a play!");
            break;

        case 
400
            print(
"I can buy shoes, an outfit, tickets to a play, and a weekend getaway!");
            break;

        default:
            print(
"I'm buying a Playstation 3 to use as a footrest while playing my XBox 360!");
    }
?>

</body>
</html>

You can also add conditions to the cases within the switch statement:

For example:switch2.php


<html>
<head>
<title>switch.php</title>
</head>
<body>


<p>A Web 2 student (I prefer not to use his name) was caught ditching again and has begged to make up his exam.
Because I am such a kind and caring teacher, I have allowed Travis to take his exam after school.  Here is his score:  
</p> 

<p>Travis 89.9</p>



<p>Let's use PHP to display Travis's grade after the ditching adjustment:</p>
<?php
//These are the variables to hold the score and the grade
$travisscore=89.9;
$travisgrade="A"//just a starting value, don't get your hopes up.

//Here is the switch statement to determine  
//The student grade.

switch($travissscore)
{
case (
$travissscore 60):
    
$travissgrade="F";
    break;
case (
$travissscore 70):
    
$travissgrade="D";
    break;
case (
$travissscore 80):
    
$travissgrade="C";
    break;
case (
$travissscore 90):
    
$travissgrade="B";
    break;
default:
    
$travissgrade="A";
}

//Ditching adjustment
$travissgrade "F"//ha ha

//Display the grade
echo "<strong>Travis, you didn't do very well on your test.  You got an "$travissgrade .".</strong>";

//Just kidding travis =)
?>

</body>
</html>