Switching
Having multiple if statements in one place is ugly, slow, and prone to errors. Consider the code in Listing 39.3.
Listing 39.3. How Multiple Conditional Statements Lead to Ugly Code
<?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.
Listing 39.4. Using a switch/case Block ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access