Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several code-lines in a script, we can use loops to perform a task like that.
By using loops statements we can decrease the number of code lines.
In PHP, there are following looping statements:
while – loops through a block of code as long as the specified condition is true
do…while – In this loop a statement is repeats the loop as long as the specified condition is true
for – loops through a block of code a specified number of times
foreach – loops through a block of code for each element in an array
while Loop- The while loop executes a block of code untill the specified condition is true.
Syntax:
while (condition) {
code ;
}
Example:
$a = 5;
while($x <= 10) { echo “The number is: $a “; $a++; } ?>
OUTPUT:
The number is:5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
do…while Loop-The do…while loop will always execute the block of code atleast once, and then check the condition, and repeat the loop till the specified condition is true.
Syntax:
do {
code ;
} while (condition);
Example:
$a= 5;
do {
echo “The number is: $a
“;
$a++;
} while ($a <= 5); ?>
OUTPUT:
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
for Loop: for loop is used when the user knows in advance that how many times the code should be executed.
Syntax:
for (initialization; condition; increment) {
code ;
}
Example:
for ($a= 0; $a <= 5; $a++) { echo “The number is: $a “; } ?>
OUTPUT:
0
1
2
3
4
5
foreach Loop: It is used to in arrays and is used to loop through each key/value pair in an array.
Syntax:
foreach ($array as $value) {
code ;
}
In each loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
$colors = array(“red”, “green”, “blue”, “yellow”);
foreach ($colors as $value) {
echo “$value
“;
}
?>
OUTPUT:
red
green
blue
yellow