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.
foreach iterates over array elementslist() destructures numeric-indexed arrays
// Using foreach with list() to unpack array values
foreach ($array as list($key, $value)) {
echo $key . " => " . $value;
}
// 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>";
}
?>
Edit the table below to see how list($name, $role) extracts data:
// 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>";
}
?>
Each sub-array is unpacked into variables. Empty positions in list() allow you to ignore values while still accessing required elements.
list() only with numeric indexeslist()