list() FunctionThe list() function in PHP allows you to assign values from an indexed array directly into individual variables in a single operation. It improves readability and is commonly used when unpacking array data.
Modify the array elements below to see how list($a, $b, $c) maps them to variables.
list() works only with numerically indexed arrays.foreach for multi-dimensional arrays.The list() construct assigns array elements to variables in the order they appear.
// Basic syntax of list() with an indexed array
list($var1, $var2, $var3) = $array;
list() with an Indexed ArrayThis example shows how array values are unpacked into separate variables.
// Assign array elements to individual variables
<?php
$array = array("apple", "banana", "cherry");
list($fruit1, $fruit2, $fruit3) = $array;
echo $fruit1;
echo $fruit2;
echo $fruit3;
?>
The output will display each fruit in sequence. Each variable receives the value from the corresponding array index.
list() with a Multi-dimensional ArrayWhen working with structured data, list() is often combined with foreach.
// Unpacking sub-array values inside a foreach loop
<?php
$fruits = array(
array("apple", 1),
array("banana", 2),
array("cherry", 3)
);
foreach ($fruits as list($name, $quantity)) {
echo "$name: $quantity<br>";
}
?>
The diagram below illustrates how array indexes map to variables when using list().
list() for readability when unpacking arrays.list() inside a foreach loop to display student names and grades.