Databases Reference
In-Depth Information
Notice that when more than one statement forms the body of the loop, the statements
are enclosed in braces. Braces are also used with the conditional if when there's more
than one statement you want to execute.
The do...while loop is almost identical to the while loop:
$x = 0;
do
{
echo "$x\n";
$x++;
} while ($x < 10);
However, there is one important difference between while and do...while : in the latter
construct, the condition is checked after the body of the loop, so the instructions be-
tween the braces are always executed at least once; if the condition is false, the loop is
not repeated.
The foreach statement is a different type of loop construct that is used to simplify
iteration through an array:
// $x is an array of strings
$x = array("one", "two", "three", "four", "five");
// This prints out each element of the array
foreach ($x as $element)
echo $element;
Functions
PHP has a large number of built-in functions that you can use to perform common
tasks. A function call is followed by parentheses that contain zero or more arguments
to the function. The following fragment uses the library function count( ) to display
the number of elements in an array:
// $x is an array of strings
$x = array("one", "two", "three", "four", "five");
// Displays 5
print count($x);
The count( ) function takes one parameter, which should be an array type. Functions
can return nothing or a value of any type; the previous example returns an integer value,
which is then output using print . When a value is returned, the function can be used
in an expression. For example, the following uses count( ) in an if statement:
// $x is an array of strings
$x = array("one", "two", "three", "four", "five");
if (count($x) >= 3)
echo "This array has several elements";
else
echo "This array contains less than three elements";
 
Search WWH ::




Custom Search