Skip to content

PHP For Loops

Loops are fundamental control structures in programming, allowing you to execute a block of code repeatedly. PHP offers several types of loops; this tutorial focuses on for and foreach.

The for loop is typically used when you know in advance exactly how many times you want the loop to run. It uses a counter to track the number of iterations.

for (expr1; expr2; expr3) {
// code to be executed;
}

Components:

  • expr1 (Initialization): Executed once at the beginning of the loop. Typically used to initialize a loop counter (e.g., $i = 0).
  • expr2 (Condition): Evaluated before each loop iteration. If it evaluates to true, the loop continues. If it evaluates to false, the loop terminates.
  • expr3 (Increment/Decrement): Executed at the end of each loop iteration. Typically used to modify the loop counter (e.g., $i++).

Example: Display numbers from 1 to 5

<?php
declare(strict_types=1);
echo "Counting from 1 to 5:\n";
for ($i = 1; $i <= 5; $i++) {
echo "The number is: {$i} <br>";
}
?>

Output:

Counting from 1 to 5:<br>The number is: 1 <br>The number is: 2 <br>The number is: 3 <br>The number is: 4 <br>The number is: 5 <br>

The foreach loop provides an easy way to iterate over arrays and other iterable objects (like those implementing the Iterator interface). It simplifies looping through collections without needing to manage counters or check array bounds.

foreach ($iterable as $value) {
// code to be executed using $value;
}

In each iteration, the value of the current element from $iterable is assigned to $value, and the internal pointer of the iterable is advanced.

foreach ($iterable as $key => $value) {
// code to be executed using $key and $value;
}

This form assigns both the key (array index or object property name) and the value of the current element in each iteration.

Example: Display colors from an array

<?php
declare(strict_types=1);
$colors = ["red", "green", "blue", "yellow"];
echo "Available colors (values only):<br>";
foreach ($colors as $value) {
// Using htmlspecialchars for safe output in HTML context
echo htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . "<br>";
}
echo "<br>Available colors (keys and values):<br>";
$settings = ['theme' => 'dark', 'fontSize' => 12, 'showTips' => true];
foreach ($settings as $key => $value) {
echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8') . ": " .
htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8') . "<br>";
}
?>

Output:

Available colors (values only):<br>red<br>green<br>blue<br>yellow<br><br>Available colors (keys and values):<br>theme: dark<br>fontSize: 12<br>showTips: 1<br>

foreach is generally the preferred way to loop through arrays and objects when you need to process each element.

You will learn more about arrays in the dedicated PHP Arrays chapter.