How to Use list() Function in PHP: Syntax and Examples
In PHP, the
list() function is used to assign variables from an array in one operation. It works by unpacking the array values into separate variables based on their order. This is useful for quickly extracting multiple values from an indexed array.Syntax
The list() function assigns variables from an array in order. It takes a comma-separated list of variables inside parentheses. The array to unpack is placed on the right side of the assignment.
- list($var1, $var2, ...): Variables to assign values to.
- =: Assignment operator.
- $array: Indexed array whose values will be assigned.
php
list($var1, $var2, $var3) = $array;
Example
This example shows how to use list() to assign three variables from an array of three values.
php
<?php $array = ['apple', 'banana', 'cherry']; list($fruit1, $fruit2, $fruit3) = $array; echo $fruit1 . "\n"; echo $fruit2 . "\n"; echo $fruit3 . "\n"; ?>
Output
apple
banana
cherry
Common Pitfalls
Common mistakes when using list() include:
- Using
list()with associative arrays (it only works with indexed arrays). - Not matching the number of variables to the number of array elements (extra variables get
null, missing variables ignore extra elements). - Using keys inside
list()(keys are ignored, only order matters).
php
<?php // Wrong: Using list() with associative array $assoc = ['a' => 1, 'b' => 2]; list($x, $y) = $assoc; echo $x . ", " . $y . "\n"; // Outputs: 1, 2 but keys are ignored // Right: Use indexed array $indexed = [1, 2]; list($x, $y) = $indexed; echo $x . ", " . $y . "\n"; ?>
Output
1, 2
1, 2
Quick Reference
| Usage | Description |
|---|---|
| list($a, $b) = $array; | Assigns first two values of indexed array to $a and $b |
| list($a, , $c) = $array; | Skips second value, assigns first and third |
| list() = $array; | No variables assigned, just discards values |
| list($a) = []; | Assigns null to $a if array is empty |
Key Takeaways
Use list() to assign variables from indexed arrays by order.
list() does not work with associative arrays; keys are ignored.
Match the number of variables to array elements to avoid unexpected nulls.
You can skip values by leaving empty positions in list().
list() is a simple way to unpack array values into variables.