Introducing array_column() in PHP 5.5

Earlier today, David Soria Parra declared a feature freeze on PHP 5.5 and tagged php-5.5.0beta1, but not before merging in pull request #257, which includes my humble addition to the PHP programming language: array_column().

The story of array_column() begins at PHP Tek in 2008. As I recall, it was Spooons who suggested it to me. It is functionality that nearly every developer has to implement in user-land code at some point in their careers, so I felt it only natural that it be built into the language, so I did just that.

My original patch for array_column() was written for PHP 5.2, but it sat around collecting dust for many years, until April of last year, when PHP moved to git and GitHub. That’s when it became easy enough to apply the patch and send a pull request, which I did. It wasn’t quite that simple, though, since I had to follow the official PHP project RFC process, but it wasn’t a pain either.

My goal for array_column() was simplicity. Many implement the functionality in different ways, and many call the function by other names (such as “pluck”), but I wanted to keep it simple and recognizable. It follows this function signature:

array array_column(array $input, mixed $columnKey[, mixed $indexKey])

Given a multi-dimensional array of data, array_column() returns the values from a single column of the input array, identified by the $columnKey. Optionally, you may provide an $indexKey to index the values in the returned array by the values from the $indexKey column in the input array.

For example, using the following array of data, we tell array_column() to return an array of just the last names, indexed by their record IDs.

$records = array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
$lastNames = array_column($records, 'last_name', 'id');

If we call print_r() on $lastNames, you’ll see a resulting array that looks a bit like this:

[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe

And that’s all there is to it. I hope you find my little addition to the PHP language helpful. I had a lot of fun writing it, and following the PHP RFC process was a great learning experience.