Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

format, and stores all its output in $i. You can make the command as long or
as complex as you like, including piping to other programs. You can also use
PHP variables inside the command.


Switching


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


LISTING 47.3 How Multiple Conditional Statements Lead to Ugly Code


Click here to view code image


<?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, the code in Listing 47.3 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 47.4.


LISTING 47.4 Using a switch/case Block


Click here to view code image


<?php
$cat_age = 3;
switch ($cat_age) {
case 1:
echo "Cat age is 1";
Free download pdf