PHP foreach Loop

Updated: April 20th, 2022, 09:28:35 IST
Published: April 20th, 2022
PHP foreach Loop
Title: PHP foreach Loop

The PHP foreach loop executes only on arrays, and is used to loop through each key/value pair in an array. The foreach loop in PHP executes through a block of code for each element in an array.

PHP foreach

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Syntax

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

PHP foreach loop iteration, the current array element's value is assigned to $value, and the array pointer is moved by one until it reaches the last array element.

Examples #1

The following example will output the values of the given array ($days):

<?php
$days = array("monday", "tuesday", "friday", "sunday");

foreach ($days as $value) {
  echo "$value <br>";
}
?>

Example #2

The following example will output both the keys and the values of the given array ($age):

<?php
$age = array("Sam"=>"35", "Rock"=>"27", "Jack"=>"43");

foreach($age as $n => $val) {
  echo "$n = $val<br>";
}
?>