O'Reilly logo

Ubuntu Unleashed 2014 Edition: Covering 13.10 and 14.04,Ninth Edition by Paul Hudson, Andrew Hudson, Matthew Helmke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required