Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

662 LESSON 24: Taking Advantage of the Server


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 ()

Furthermore, individual values also evaluate to true or false on their own. Any variable
set to anything other than 0 or an empty string ("" or '') will evaluate as true, including
an array with no elements in it. So if $var is set to 1, the following condition will evalu-
ate as true:
if ($var) {
echo "True.";
}

If you want to test whether an array is empty, use the built-in function empty(). So if
$var is an empty array, empty($var) will return true. Here’s an example:
if (empty($var)) {
echo "The array is empty.";
}

You can find a full list of PHP operators at http://www.php.net/manual/en/
language.operators.php.

Loops
PHP supports several types of loops, some of which are more commonly used than
others. As you know from the JavaScript lesson, loops execute code repeatedly until a
Free download pdf