PHP For & Foreach Loop
ADVERTISEMENTS
If you have a block of code and you want to execute this block of code many times you will be needed For loop statement to execute the script till N times.
PHP For loop
PHP For loop uses three parameters to execute the script at the specified time.
Syntax of the php for loop
for (initial counter; test counter; increment/decrement counter) {
execute a block of code;
}
execute a block of code;
}
Example of the php for loop:
<?php
for ( $m = 0; $m <= 6; $m++ )
{
echo "Hello For Loop";
echo "\n";
}
?>
Output:
Hello For Loop
Hello For Loop
Hello For Loop
Hello For Loop
Hello For Loop
Hello For Loop
Hello For Loop
PHP Foreach loop
PHP Foreach loop works only on an array, Array can be indexed array or associative array.
Foreach loop on an indexed array:
Syntax of the foreach loop on an indexed array
foreach ( $array as $value ) {
execute statement or block of code;
}
execute statement or block of code;
}
Example of the foreach loop on an indexed array:
<?php
$days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
foreach ( $days as $value )
{
echo "It's " . $value . "\n";
}
?>
Output:
It's Monday
It's Tuesday
It's Wednesday
It's Thursday
It's Friday
It's Saturday
It's Sunday
Foreach loop on the Associative array:
Syntax of the foreach loop on the associative array
foreach ( $array as $key => $value ) {
execute statement or block of code;
}
execute statement or block of code;
}
Example of the foreach loop on the associative array:
<?php
$days = array("ID"=>"1256", "Name"=>"John Will", "Age"=>25, "Profession"=>"Web Developer");
foreach ( $days as $key => $value )
{
echo $key . " is " . $value . "\n";
}
?>
Output:
ID is 1256
Name is John Will
Age is 25
Profession is Web Developer