Definition and Usage
- PHP Version
- 4+
The for statement is a loop that repeats code a specific number of times or over a specified range.
It is very useful for repeatedly executing code a set number of times and is one of the essential basic loops you should know in PHP.
Basic Example
for ($i = 1; $i <= 5; $i++) {
echo $i . ' ';
}
// Output: 1 2 3 4 5
This is a loop statement with an associated loop variable that has an initial value ($i = 1). It repeatedly executes a code block ({}) a specific number of times or over a specified range by comparing ($i <= 5) and incrementing or decrementing ($i++) the loop variable.
A loop variable is a variable used to control the number of iterations in a loop.
In the example above, $i is the loop variable. $i is initialized to 1, and the loop continues while the $i <= 5 condition is satisfied. In each iteration, $i is incremented by 1, and the loop ends when the condition is no longer satisfied.
Syntax
The for statement consists of three optional expressions enclosed in parentheses (()) and separated by semicolons (;), followed by a code block ({}).
for (initialization; condition; increment/decrement) {
// Code block to execute
}
initialization
This is the initialization expression. It sets the initial value of the loop variable. This expression is executed only once when the loop starts. It is optional.
condition
This is the condition expression that is evaluated against the loop variable to determine whether to execute the code block ({}). It is optional.
- If this condition evaluates to
true, the code block ({}) is executed. - If this condition evaluates to
false, theforstatement is no longer executed and terminates. - If this condition is omitted, it is considered to be
true. This results in an infinite loop. Therefore, you should be careful when omitting the condition expression. Unless you intentionally need to create an infinite loop, it is generally recommended not to omit the condition expression.
increment/decrement
After the code block ({}) is executed, the increment/decrement expression changes the value of the loop variable. It uses an operation to increment or decrement the loop variable so that the code can be repeated a specific number of times or over a specified range. It is optional.
Note!
The three optional expressions used here (initialization; condition; increment/decrement) can be omitted individually, but the semicolons (;) cannot be omitted.
Execution Order of the for Statement
When the for statement is executed, it follows the sequence below.
- If the initialization expression,
initialization, is not omitted,initializationis executed. - The
conditionis evaluated. If the condition evaluates totrue, the code block ({}) is executed. However, if it evaluates tofalse, theforstatement is no longer executed and terminates. If this condition is omitted, it is considered to betrue. - If the
conditionevaluates totrue, the code block ({}) is executed. - After the code block (
{}) is executed, ifincrement/decrementis not omitted, the value of the loop variable is changed usingincrement/decrement. - The process returns to the second step, where the
conditionis evaluated. The subsequent steps are repeated.
Note
PHP supports an alternative syntax for the for control structure (Alternative syntax for control structures). It is also known as "colon syntax". This syntax is mainly used to improve readability when mixing HTML and PHP.
for Loop
<?php for (initialization; condition; increment/decrement): ?>
<?php // Code block to execute ?>
<?php endfor; ?>
<?php for ($i = 1; $i <= 5; $i++): ?>
<?php echo $i . ' '; ?>
<?php endfor; // Output: 1 2 3 4 5 ?>
Examples
Let's look at some examples of using the for loop.
Code That Repeats a Specific Number of Times
/* Print numbers from 1 to 10 */
for ($i = 1; $i <= 10; $i++) {
echo $i . ' ';
}
// Output: 1 2 3 4 5 6 7 8 9 10
/* Print numbers from 10 to 1 */
for ($i = 10; $i >= 1; $i--) {
echo $i . ' ';
}
// Output: 10 9 8 7 6 5 4 3 2 1
Array Iteration
It is commonly used to iterate over each element of an array.
$fruits = ['apple', 'banana', 'cherry'];
$fruits_length = count($fruits);
for ($i = 0; $i < $fruits_length; $i++) {
echo $fruits[$i] . ' ';
}
// Output: apple banana cherry
Code Explanation
The count() function counts the number of elements (array length) in an array and returns an integer. An empty array has a length of 0.
As shown in the example above, the for loop is often used for arrays. However, when using the foreach loop to iterate over arrays or objects and process each element, it provides better readability and more concise code.
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo $fruit . ' ';
}
// Output: apple banana cherry
Code Explanation
The foreach loop is a fundamental construct used to iterate through all elements of an array or object.
However, when you need to control iteration using indexes or manage the number of iterations directly, the for loop may be more appropriate.
for Statement Without initialization
The initialization expression, initialization, can be omitted. Let's look at the following example.
$i = 0;
for (; $i < 4; $i++) {
echo $i . ' ';
}
// Output: 0 1 2 3
for Statement Without condition
The condition can also be omitted. Let's look at the following example.
for ($i = 0; ; $i++) {
if ($i > 3) {
break;
}
echo $i . ' ';
}
// Output: 0 1 2 3
Code Explanation
The break keyword immediately terminates the current loop and transfers control to the code that follows it.
In this case, you need to take measures to prevent an infinite loop from occurring. In the example above, a conditional (if) statement and the break keyword are used to prevent an infinite loop.
Things to Keep in Mind
There are several things to keep in mind when using the for statement.
Preventing Infinite Loops
For example, if the condition in a for statement always evaluates to true, it can result in an infinite loop. An infinite loop can cause the program to become unresponsive because the loop never terminates.
The following are some examples of for statements that cause infinite loops.
When the Condition Is Always True
for ($i = 0; $i >= 0; $i++) {
echo $i; // Prints numbers continuously increasing from 0
}
When the Loop Variable Is Not Changed
for ($i = 1; $i = 1; $i++) {
echo $i; // Continuously prints 1
}
When the condition Is Omitted Without Additional Measures
for ($i = 0; ; $i++) {
echo $i; // Infinite loop without a condition
}
When the condition Is Incorrect
for ($i = 0; $i != 10; $i--) {
echo $i;
}
Repeatedly Calculating the Array Length in the condition of a Loop
Repeatedly calculating the array length in a loop is inefficient. Since the array length does not change, storing the length in a variable before entering the loop can avoid unnecessary operations on each iteration. This can improve performance.
For example, the following is not recommended.
$fruits = ['apple', 'banana', 'cherry'];
for ($i = 0; $i < count($fruits); $i++) { // count($fruits) is calculated repeatedly
echo $fruits[$i];
}
Use it as shown in the following example.
$fruits = ['apple', 'banana', 'cherry'];
$fruits_length = count($fruits); // count($fruits) is calculated only once
for ($i = 0; $i < $fruits_length; $i++) {
echo $fruits[$i];
}
This way, count($fruits) is calculated only once, which can reduce resource usage.