HTML and CSS Reference
In-Depth Information
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.oper-
ators.php.
Loops
PHP supports several types of loops, some of which are generally more commonly used
than others. As you know from the JavaScript lesson, loops execute code repeatedly until
a condition of some kind is satisfied. PHP supports several types of loops: do...while ,
while , for , and foreach . I discuss them in reverse order.
foreach Loops
The foreach loop was created for one purpose—to enable you to process all the ele-
ments in an array quickly and easily. The body of the loop is executed once for each item
in an array, which is made available to the body of the loop as a variable specified in the
loop statement. Here's how it works:
$colors = array('red', 'green', 'blue');
foreach ($colors as $color) {
echo $color . “\n”;
}
This loop prints each of the elements in the $colors array with a linefeed after each
color. The important part of the example is the foreach statement. It specifies that the
array to iterate over is $colors , and that each element should be copied to the variable
$color so that it can be accessed in the body of the loop.
 
 
 
Search WWH ::




Custom Search