PHP loops
are used to loop through a block of code a specific number of times.
General Syntax
for(initialization; condition; increment/decrement){
//Block of code to be executed
}
Source Code
for ($i=1; $i<=5; $i++){
echo "The Number is : ".$i."<br />";
}
Let us describe every term of for loop.
initialization:
It is used to set the initial value of the variable.Condition:
It checks the condition and if the condition is true then the loop execution will be continue, otherwise the execution of loop will be end.
Increment/decrement:
It is used to increase or decrease the value of variable.
In PHP, each loop is used to traverse the array elements.
foreach ($array as $key => $value) {
// block of code to be executed
}
Here,$array
denotes the array variable that contains the array element and $key
specifies to array element keys and $value
denotes the array value with respect to $key
.
Source Code
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
// foreach loop
foreach ($fruits as $fruit) {
echo $fruit . '<br>';
}
Note: In indexed arrays, =>
$value part is omitted in foreach
loop.
Source Code
<?php
$fruits = [
'mango' => 200,
'orange' => 245,
'garpes' => 130
];
foreach ($fruits as $fruit => $cost) {
echo " $fruit, having cost: " .$cost '<br>';
}
?>