HTML and CSS Reference
In-Depth Information
echo “Variable set to something other than 0.”;
}
When you add an
else
block to a conditional statement, it means that the statement will
always do something. If the expression is true, it will run the code in the
if
portion of
the statement. If the expression is not true, it will run the code in the
else
portion.
Finally, there's
elseif
:
if ($var == 0) {
echo “Variable set to 0.”;
} elseif ($var == 1) {
echo “Variable set to 1.”;
} elseif ($var == 2) {
echo “Variable set to 2.”;
} else {
echo “Variable set to something other than 0, 1, or 2.”;
}
As you can see,
elseif
allows you to add more conditions to an
if
statement. In this
case, I added two
elseif
conditions. There's no limit on
elseif
conditions—you can
use as many as you need. Ultimately,
elseif
and
else
are both conveniences that enable
you to write less code to handle conditional tasks.
PHP Conditional Operators
It's hard to write conditional statements if you don't know how to write a Boolean
expression. First of all, Boolean means that an expression (which you can think of as a
statement of fact) is either true or false. Here are some examples:
1 == 2 // false
'cat' == 'dog' // false
5.5 == 5.5 // true
5 > 0 // true
5 >= 5 // true
5 < 10 // true
PHP also supports logical operators, such as “not” (which is represented by an exclama-
tion point), “and” (
&&
), and “or” (
||
). You can use them to create expressions that are
made up of multiple individual expressions, like these:
1 == 1 && 2 == 4 // false
'blue' == 'green' || 'blue' == 'red' // false
!(1 == 2) // true, because the ! implies “not”
!(1 == 1 || 1 == 2) // false, because ! negates the expression inside the ()
21