Switching

Having multiple if statements in one place is ugly, slow, and prone to errors. Consider the code in Listing 42.3.

LISTING 42.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 42.4.

LISTING 42.4 ...

Get Ubuntu Unleashed 2014 Edition: Covering 13.10 and 14.04,Ninth 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.