Loops in PHP
Loops in PHP are used to execute the same block of
code a specified number of times. PHP supports
following four loop types.
for − loops through a block of code a specified number of
times.
while − loops through a block of code if and as long as a
specified condition is true.
do...while − loops through a block of code once, and then
repeats the loop as long as a special condition is true.
foreach − loops through a block of code for each element in
an array.
For Loops
Statement
The for loop statement
The for statement is used when you
know how many times you want to
execute a statement or a block of
statements.
Syntax
for (initialization; condition; increment)
{ code to be executed; }
The initializer is used to set the start value for the
counter of the number of loop iterations. A
variable may be declared here for this purpose and
it is traditional to name it $i.
initialization — it is used to initialize the counter
variables, and evaluated once unconditionally before
the first execution of the body of the loop.
condition — in the beginning of each iteration,
condition is evaluated. If it evaluates to true, the loop
continues and the nested statements are executed. If
it evaluates to false, the execution of the loop ends.
increment — it updates the loop counter with a new
value. It is evaluate at the end of each iteration.
<html>
<body>
<?php
$a = 0; $b = 0;
for( $i = 0; $i<5; $i++ ) {
$a += 10; $b += 5; }
echo ("At the end of the loop a = $a and b = $b" ); ?>
</body>
</html>
The example below defines a loop that starts
with $i=0. The loop will continued until $i is less
than, 5. The variable $i will increase by 1 each time
the loop runs:
This will produce the following result:
At the end of the loop a = 50 and b = 25
Foreach Loop
The foreach statement is used to loop through
arrays. Foreach pass the value of the current array
element is assigned to $value and the array pointer is
moved by one and in the next pass next element will
be processed.
Syntax
foreach (array as value)
{ code to be executed; }
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value ) {
echo "Value is $value <br />"; }
?>
</body>
</html>
This will produce the following result :
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
There is one more syntax of foreach loop,
which is extension of the first.
foreach($array as $key => $value){
// Code to be executed;
}
<?php
$superhero = array(
"name" => "Peter Parker", "email" =>
"peterparker@mail.com", "age" => 18
);
// Loop through superhero array
foreach($superhero as $key => $value){
echo $key . " : " . $value . "<br>";
}
?>
Output
name : Peter Parker
email : peterparker@mail.com
age : 18