PHP » Control Structures » foreach

Syntax:
foreach ($array as $element) {
   // code using each $element
}

Repeats a block of code for every element in an array.

foreach is a very convenient statement when iterating through an array. It eliminates the need to to manually check the size of an array.

Examples

Code:
<?php

$fruits = array("apple", "banana", "orange");
$words = array("un" => "one",
   "deux" => "two",
   "trois" => "three");

foreach ($fruits as $fruit) {
   print "$fruit ";
}

print "<br>";

// alternative method, equivalent to foreach
for ($i = 0; $i < count($fruits); $i++) {
   print "$fruits[$i] ";
}

print "<br><br>";

// with associative arrays
foreach ($words as $key => $value) {
   print "$key => $value<br>";
}

?>
Output:
apple banana orange
apple banana orange

un => one
deux => two
trois => three
Explanation:

foreach loops with both indexed and associative arrays are shown. For comparison, a for loop is also included.

See Also: