php: IF versus SWITCH
Often times, a PHP developer will need to display different information depending on the circumstances. In the case of our SE Content Management System, there are dozens of these scenarios: from where to display the image gallery on a particular page to whether or not to show breadcrumbs. In every instance, we have to determine how to evaluate the situation. Is it a simple show or don’t show item, or are there several possible outcomes?
In this example, we will be using the months of the year as our ‘variable’.
First we must define the current month:
php:<?php $currentmonth = date("m"); ?>Now, if we wanted to introduce special code in only one month, such as saying ‘Happy New Year’ in January, then an IF statement would work just fine:
php:<?php if ($currentmonth == '01') { ?>You see that the if statement is always enclosed in parenthesis and the result is always enclosed in squiggly brackets. In this example, we chose to output in HTML, so we had to close and re-open our php tags. We could have also chosen to do this:
<strong>Happy New Year!</strong>
<?php } ?>
php:<?php if ($currentmonth == '01') {Lets say that you needed a ‘Happy New Year’ for January, ‘Happy Valentines Day’ for February, ‘Happy Thanksgiving’ for November and ‘Merry Christmas’ for December. An If statement is not practical for this situation, so we need to use the php SWITCH statement instead. With a switch statement, we first present the variable:
echo "Happy New Year!";
} ?>
php:<?php switch ($currentmonth) {Next, we present each ‘case’, followed by the intended output and a break. Lets start with January, which is ‘01′:
php:case 01:
echo "Happy New Year";
break;
Now, lets put it all together:
php:<?php switch ($currentmonth) {
case 01:
echo "Happy New Year";
break;
case 02:
echo "Happy Valentines";
break;
case 11:
echo "Happy Thanksgiving";
break;
case 12:
echo "Merry Christmas";
break;
default:
echo "Just another month...";
}
?>
You see that we also added a ‘default’ condition for all other months. This is, of course not required, but it is often useful.
Compatibility:
As this is a php tutorial, a php-capable server is required for this code to function properly.
That’s all folks!
If you have an idea or article that you would like to contribute, send it on! We’re always looking for good, quality articles. Note that we will not republish an article that has been published elsewhere, so keep it original!



