Switching
Having multiple if
statements in one place is ugly, slow, and prone to errors. Consider the code in Listing 39.3.
<?php $cat_age = 3; if ($cat_age == 1) { echo "Cat age is 1"; } else { if ($cat_age == 2) { echo "Cat age is 2"; } else { if ($cat_age == 3) { echo "Cat age is 3"; } else { if ($cat_age == 4) { echo "Cat age is 4"; } else { echo "Cat age is unknown"; } } } }?>
Even though it certainly works, it is a poor solution to the problem. Much better is a switch
/case
block, which transforms the previous code into what’s shown in Listing 39.4.
Get Ubuntu Unleashed 2013 Edition: Covering 12.10 and 13.04, Eighth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.