The foreach loop in PHP is a simple and convenient way to iterate over arrays. Unlike traditional loops such as for or while, it directly accesses array elements without managing an index.
// Basic foreach syntax
foreach ($array as $value) {
echo $value;
}
// Foreach with key and value
foreach ($array as $key => $value) {
echo $key . " => " . $value;
}
// Looping through an indexed array
<?php
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
// Looping through an associative array
<?php
$age = array("Peter" => 35, "John" => 30, "Doe" => 25);
foreach ($age as $name => $age_value) {
echo "$name is $age_value years old.<br>";
}
?>
// Nested foreach loop with multidimensional array
<?php
$students = array(
"Class A" => array("Alice", "Bob"),
"Class B" => array("Charlie", "David")
);
foreach ($students as $class => $names) {
echo "$class:<br>";
foreach ($names as $student) {
echo "- $student<br>";
}
echo "<br>";
}
?>
Each foreach iteration fetches values directly from the array. For associative arrays, both keys and values are accessible. Nested loops allow traversal of complex data structures.
Select a loop type to see how PHP "thinks" through the data structure.
Click a button to start simulation...
The flow below conceptually represents how foreach processes array elements sequentially:
Array ➜ Element ➜ Execute Block ➜ Next Element
foreach for array traversal for clarity.foreach.foreach.