The Switch Statement

Don’t let your php code get bogged down by tonnes of IF and ELSE statements. Multiple IF and ELSE statements can look very messy and are a nightmare to decipher when you look back at your code on a later date. Instead, try using a Switch statement. It takes less time to type, looks neater and is executed slightly quicker than multiple IF statements.

So, instead of saying:

<?php
if ($colour=="red") {
print "Stop";
}
if ($colour=="amber") {
print "Get Ready";
}
if ($colour=="green") {
print "Go!";
}
if (($colour!="red") && ($colour!="amber") && ($colour!="green")) {
print "The traffic lights are broken!";
}
?>

 …you could say:

<?php
switch ($colour) {
case “red”:
print “Stop”;
break;
case “amber”:
print “Get Ready!”;
break;
case “green”:
print “Go!”;
break;
default:
print "The traffic lights are broken!";
}
?>

Easy huh?

PS- I just realised, I got the amber thing wrong. Apparently amber does not mean Get Ready at all! According to the experts:

AMBER means 'Stop' at the stop line. You may go on only if the AMBER appears after you have crossed the stop line or are so close to it that to pull up might cause an accident. (taken from http://www.officialclassics.com/tips.php).

 Well, now you know! (David Connelly)

Live Assistant

Hello there! I'm Rachael and I'm your live helper for today.

How can I help you?

Quote Request

If you are looking for a quick quotation then why not submit a quote request? It only takes a few moments and we always respond quickly.