O'Reilly logo

Ubuntu Unleashed 2013 Edition: Covering 12.10 and 13.04, Eighth Edition by 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 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 ...

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