PHP foreach

Last Updated: February 26, 2022

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.

PHP Iterate over indexed array

Syntax

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

Iterate PHP indexed array to get key and value

<?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 an associative array with key and value pair

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

foreach iteration over an associative array to get key and value pair

$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
Test