← Back to Chapters

PHP Foreach Loop with list()

? PHP Foreach Loop with list()

? Quick Overview

The foreach loop in PHP can be combined with the list() construct to directly unpack values from multidimensional arrays into variables, making iteration cleaner and more readable.

? Key Concepts

  • foreach iterates over array elements
  • list() destructures numeric-indexed arrays
  • Works best with predictable array structures

? Syntax / Theory

? View Code Example
// Using foreach with list() to unpack array values
foreach ($array as list($key, $value)) {
    echo $key . " => " . $value;
}

? Code Example 1: Basic Usage

? View Code Example
// Iterating over a multidimensional array using list()
<?php
$persons = array(
array("Peter", 35, "Manager"),
array("John", 30, "Developer"),
array("Doe", 25, "Designer")
);

foreach ($persons as list($name, $age, $position)) {
echo "$name is $age years old and works as a $position.<br>";
}
?>

?️ Interactive Sandbox

Edit the table below to see how list($name, $role) extracts data:

Click "Run" to see output...

?‍? Code Example 2: Skipping Values

? View Code Example
// Skipping the age value using an empty position in list()
<?php
$students = array(
array("Alice", 20, "A"),
array("Bob", 22, "B"),
array("Charlie", 21, "A+")
);

foreach ($students as list($name, , $grade)) {
echo "$name has grade $grade.<br>";
}
?>

? Live Output / Explanation

Each sub-array is unpacked into variables. Empty positions in list() allow you to ignore values while still accessing required elements.

? Use Cases

  • Processing database result sets
  • Handling CSV or tabular data
  • Clean extraction of structured array data

✅ Tips & Best Practices

  • Ensure all sub-arrays follow the same structure
  • Use list() only with numeric indexes
  • Keep variable naming meaningful for clarity

? Try It Yourself

  • Create a students array and print names with grades
  • Add subjects and extract all values using list()
  • Practice with deeper nested arrays