|
|
Loops I - The for Loop
What Are Loops?
Often you may need to execute the same block of code several times consecutively. Loops provide a convenient structure in which to do this.
The for Loop
A for is usually used to execute a block of code a specified number of times. The basic structure of a for loop is:
for ( initialization ; condition ; counter ) {
//Do something.
}
The for loop takes three parameters:
This code:
for ( $i=1 ; $i<=10 ; $i++ ) {
echo("$i<br>");
}
Produces the following result:
1
2 3 4 5 6 7 8 9 10
So, what's going on here?
Note that each of the 3 parameters to the for loop is optional. Both of the following examples are valid in PHP:
for ( ; ; ) {
$i++;
echo("$i<br>");
}
for( ; ; $i++) {
echo("$i<br>");
}
These will both produce the same result - an infinite loop, which will continue incrementing $i and outputting its value until the user stops the script manually.
The foreach Loop
A foreach loop iterates through each item in an array. It can take one of two forms:
foreach ( $array as $value ) {
//Do something.
}
foreach( $array as $key => $value ) {
//Do something.
}
In either structure, $array must be an existing PHP array. The loop will assign each element of that array to $value in turn, and, if $key is specified, that will be assigned the key associated with the $value. An example:
$myFamily['mum'] = "Jane";
$myFamily['dad'] = "James";
$myFamily['grandma'] = "Josephine";
$myFamily['grandad'] = "John";
foreach( $myFamily as $relative => $name ) {
echo("My $relative's name is $name.<br>");
}
The above code produces the following result:
My mum's name is Jane.
My dad's name is James. My grandma's name is Josephine. My grandad's name is John. Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
|