Databases Reference
In-Depth Information
The
switch...case
construct allows you to easily select between several possible values,
as in the following example:
switch ($x)
{
case 1:
echo "x is 1";
break;
case 2:
echo "x is 2";
break;
case 3:
echo "x is 3";
break;
default:
echo "x is not 1, 2, or 3";
}
The
default
section is executed if the
switch
value doesn't match any of the
case
values.
The
break
keyword tells PHP to leave the
switch
construct; if you leave it out, processing
will drop through to the next
case
condition, and the statements there will also be
executed. For example, if $x is one, and the first break is missing, the program would
print “x is 1”, and then continue into the next case, and also print “x is 2”.
Equality is tested with the double-equals (
==
) syntax:
$x = 4;
if ($x == 4)
echo "x is four!";
It's a very common mistake to forget to write the second equals symbol (
=
) in an equality
test. PHP considers a variable assignment operation to have a
true
value, so the test
will always succeed. For instance, the test below will always succeed, and so the mes-
sage
"x is four!"
will be printed whatever the value of
x
—for example, 3:
$x = 3;
if ($x = 4)
echo "x is four!";
A triple-equals operator (
===
) can also be used to test if the parameters are both equal
and of the same type:
$x = 0;
// This prints, since 0 and false are the same value
if ($x == false)
echo "$x is false";
// This doesn't print, because 0 and false aren't the same type
if ($x === false)
echo "$x is false";