|
|
Decisions II - The switch Statement
The switch Statement
The switch statement, like the if...elseif...else statement covered in the previous part, selects one of several blocks of code to execute based on a condition. It takes the form:
switch(value) {
case value1:
//Code to execute if variable == value1.
break;
case value2:
//Code to execute if variable == value2.
break;
case value3:
//Code to execute if variable == value3.
break;
default:
//Code to execute if variable does not equal value1, value2, or value3.
}
Here, PHP compares 'value' to each of the specified cases in order. If they are equal, the block of code under the relevant 'case' statement is executed, until the break keyword is reached. If none of the 'case' values match, the code under the default statement is executed. The default block is optional, and if it is not included, none of the code within the 'switch' statement will be executed if no 'case' statments match.
Here's an example of both the if and switch statements, as well as some of the string formatting we covered in earlier tutorials:
<?php
$weekday = date("w");
switch($weekday) {
case 0:
$day = "Sunday";
break;
case 1:
$day = "Monday";
break;
case 2:
$day = "Tuesday";
break;
case 3:
$day = "Wednesday";
break;
case 4:
$day = "Thursday";
break;
case 5:
$day = "Friday";
break;
case 6:
$day = "Saturday";
}
/* Note that the above is purely for demonstration of the 'switch' statement.
For practical purposes,
$day = date("l");
would achieve the same result with far less effort!
See the link (below) to the PHP manual for more information.
*/
if(date("a")=="am") {
$time = "morning";
} else {
$time = "afternoon";
}
echo("It is $day $time.");
?>
This uses PHP's date() function (documentation for which can be found here), which returns a string containing information about the current date and time. In the first call to date(), passing "w" as an argument causes the function to return a number from 0 to 6 representing the day of the week. Here we see another example of PHP's weak typing - although the date() function has returned a string, we have specified integers in each of the 'case' statements. PHP automatically converts the $weekday string to an integer before performing the comparison.
In the second call to date(), we pass "a" as an argument. This time, the function returns either "am" or "pm" as appropriate for the current time of day, and we use a simple if statement to check whether it is morning or afternoon, before outputting the result of thse two calls to date() with the echo() construct. The result might be, for example:
It is Tuesday afternoon.
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|