Array unpacking in PHP

One of PHP’s less known language constructs is list(), very useful for unpacking indexed arrays. Consider the following simple example denoting its usage:

<?php

//populate an array with values
$record= array('me', '1.800.123.4567', 'me@example.com');

//unpack the array into variables, skipping the phone number
list($name, , $email) = $record;

//print the output
echo("name: $name; email: $email");

?>

This clean, readable, scalable approach is great for processing data records, unpacking an SQL result row, etc. The only shortcoming, list() cannot be applied to an associative array. This makes sense, list() would have to assume an ordering on the keys. In general, unpacking an associative array is messier and why would you anyway? The key=>value pairs are already mapped.

Nevertheless, if you must unpack an associative array, there are options: extract() unpacks associative arrays into variables matching the names of their respective keys. Warning: 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