PHP foreach

Last Updated: June 13, 2021

foreach can be used to traverse the array elements (key/value pair).

foreach can be used to iterate either indexed array or associative array.

foreach can be used only with array

You do not need to know the number of elements of the array to iterate. foreach can start with the first element and end with the last element.

You can understand the foreach with following example.

Iterate over indexed array

Syntax

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

Iterate indexed array with foreach

<?php
$week = array("Sun", "Mon", "Tue","Wed","Thu","Fri"."Sat");
foreach ($week as $day) {
	echo $day . '<br>';
}
?> 

// Output
Sun
Mon
Tue
Wed
Thu
Fry
Sat

Iterate over associative array

This is how you define associative array with key and value pair

// $var = array("key1"=>"Value1", "key2"=>"Value2", "keyN"=>"ValueN"); 

foreach iteration over associative array

$marks = array(
    "Maths" => "75",
    "Science" => "59",
    "English" => "81"
);

foreach ($marks as $key => $value) {
    echo $key . "=" . $value . "<br>";
}


Output
Maths=75
Science=59
English=81

Summary

foreach ($week as $day) { } // iterate indexed array
foreach ($marks as $key => $value) { } // iterate associative array