Looping in PHP
Posted by tutor | Posted in PHP Tutorial | Posted on 09-07-2010-05-2008
0
Loops are programming construct which executes a block of code for a specified number of time, or while a specified condition is valid.
In general sense a loop is to help us get the repetitive job get done.
The for Loop
For loop is an iterative loop, ie it executes for a fixed number of iterations.
For loop is best for cases when you know in advance how many times the script should run.
Syntax
- for (initialization; condition; increment)
{
code to be executed;
}
Parameters:
- initialization: used to initialize a counter variable. It is executed only once when the loop begins
- condition: also called the exit condition for this loop. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. This statement is executed everytime the loop is iterated.
- increment: used to increment the counter variable. This statement is also executed at each iteration of the loop.
A semicolon is needed to separate each statement because these are separate expressions. However, no semicolon is needed after the “increment counter” expression.
Although the init and increment part are defined for initialization and increment but any piece of code can be written there.
Each of the three parameters can be empty, or have multiple expressions separated by commas.
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo “The value of i is ” . $i . “<br />”;
}
?>
</body>
</html>
The value of i isĀ 1
The value of i is 2
The value of i is 3
The value of i is 4
The value of i is 5
The foreach Loop
This loop is specially used to loop through arrays.
Syntax
- foreach ($array as $value)
{
code to be executed;
}
The value of the current array element is assigned to $value, for each iteration and the array pointer is moved by one. On the next loop iteration, you’ll be looking at the next array value.
<html>
<body>
<?php
$x=array(“apple”,”mango”,”banana”);
foreach ($x as $value)
{
echo $value . “<br />”;
}
?>
</body>
</html>
apple
mango
banana
