One of PHP’s less known language constructs is list(), very useful for unpacking indexed arrays. Consider the following simple example denoting its usage:
$record = ['me', '1.800.123.4567', 'me@example.com'];
// Unpack the array into variables, skipping the phone number
list($name, , $email) = $record;
This clean, readable, scalable approach is great for processing data records, unpacking an SQL result row, etc.
Maps / Associative Arrays
As of PHP 7.1.0 list()
can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed.
$record = [1, 2, 3, 4, 'a' => '5'];
// Unpack index 1, 3, and 'a' into variables
list(1 => $key1, 'a' => $keya, 3 => $key3) = $record;
Unpacking Maps / Associative Arrays PHP < 7.1.0
There are options: extract() unpacks associative arrays into variables matching the names of their respective keys.
There are both runtime and security issues to consider when using extract() – you will find both discussed in the PHP documentation for the function.
Reasons to favour list() over extract()
- You have control over which indices are extracted
- You have control over the naming of the variables
- list() is a language construct and will be very fast