PHP Loops - For Loop
Executes a block of code a specified number of times, or while a specified condition is true.
For Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
Parameters:
Initialization: Primarily used to initialize a variable value, setting up a counter (but can be any code that executes once at the start of the loop).
Condition: The limit for loop execution. If true, the loop continues. If false, the loop ends.
Increment: Primarily used to increment the counter (but can be any code that executes at the end of the loop).
Note: The initialization and increment parameters can be empty, or contain multiple expressions (separated by commas).
Example
The following example defines a loop with an initial value of i=1. The loop will continue to run as long as the variable i
is less than or equal to 5. Each time the loop runs, the variable i
is incremented by 1:
Example
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . PHP_EOL;
}
?>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
Foreach Loop
The foreach loop is used to iterate over arrays.
Syntax
foreach ($array as $value)
{
code to be executed;
}
On each iteration, the current array element's value is assigned to $value (and the array pointer is moved by one), until it reaches the next element.
foreach ($array as $key => $value)
{
code to be executed;
}
On each iteration, the current array element's key and value are assigned to $key and $value (and the array pointer is moved by one), until it reaches the next element.
Example
The following example demonstrates a loop that outputs the values of a given array:
Example
<?php
$x = array("Google", "tutorialpro", "Taobao");
foreach ($x as $value)
{
echo $value . PHP_EOL;
}
?>
Output:
Google
tutorialpro
Taobao
The following example demonstrates a loop that outputs the keys and values of a given array:
Example
<?php
$x = array(1 => "Google", 2 => "tutorialpro", 3 => "Taobao");
foreach ($x as $key => $value)
{
echo "Key is " . $key . ", value is " . $value . PHP_EOL;
}
?>
Output:
Key is 1, value is Google
Key is 2, value is tutorialpro
Key is 3, value is Taobao