Specifications

This HTML code has added a new form variable whose value will be “a”, “b”, “c”, or “d”. We
could handle this new variable with a series of if and elseif statements like this:
if($find == “a”)
echo “<P>Regular customer.”;
elseif($find == “b”)
echo “<P>Customer referred by TV advert.”;
elseif($find == “c”)
echo “<P>Customer referred by phone directory.”;
elseif($find == “d”)
echo “<P>Customer referred by word of mouth.”;
Alternatively, we could write a switch statement:
switch($find)
{
case “a” :
echo “<P>Regular customer.”;
break;
case “b” :
echo “<P>Customer referred by TV advert.”;
break;
case “c” :
echo “<P>Customer referred by phone directory.”;
break;
case “c” :
echo “<P>Customer referred by word of mouth.”;
break;
default :
echo “<P>We do not know how this customer found us.”;
break;
}
The switch statement behaves a little differently from an if or elseif statement. An if state-
ment affects only one statement unless you deliberately use curly braces to create a block of
statements. A switch behaves in the opposite way. When a case in a switch is activated, PHP
will execute statements until it reaches a break statement. Without break statements, a switch
would execute all the code following the case that was true. When a break statement is
reached, the next line of code after the switch statement will be executed.
Comparing the Different Conditionals
If you are not familiar with these statements, you might be asking, Which one is the best?
That is not really a question we can answer. There is nothing that you can do with one or more
else, elseif, or switch statements that you cannot do with a set of if statements. You should
Using PHP
P
ART I
42
03 7842 CH01 3/6/01 3:39 PM Page 42