A foreach loop is a control structure designed specifically for looping through collections of data, such as arrays.
Unlike a standard for loop, which relies on an incrementing counter variable to access items by their numeric index, a foreach loop automatically advances through a collection step-by-step from start to finish.
The foreach loop copies the value of the current element into a temporary variable during each lap of the loop.
<?php
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo "Fruit: $fruit\n";
}
// Outputs:
// Fruit: Apple
// Fruit: Banana
// Fruit: Orange
Each value also has a key associated with it, which you can access the key by using the $key => $value syntax.
<?php
$user = [
"name" => "Alice",
"email" => "alice@example.com",
"role" => "Admin"
];
foreach ($user as $key => $value) {
echo "$key is set to $value";
}
// Outputs:
// name is set to Alice
// email is set to alice@example.com
// role is set to Admin
This applies even if the keys are automatically generated. Notice how when creating an array without explicit keys, it uses zero-indexed numbers.
<?php
$values = ['Apple', 'Banana', 'Orange'];
foreach ($values as $key => $value) {
echo "$key => $value";
}
// outputs
// 0 => Apple
// 1 => Banana
// 2 => Value
In PHP, foreach can loop over anything that is considered an traversible.
Array - The most common iterable. This includes both ordered numeric lists and key-value pairs (associative arrays).
Traversables - This is an internal engine designation for objects that can be stepped through using a loop. While you cannot create a raw Traversable object directly, many built-in PHP objects (like database query results or file readers) implement this structure under the hood so they can be processed cleanly by loops.
If you attempt to pass a standard variable—like a string or an integer—into a foreach loop, PHP will encounter an error because those types are not iterable.