PHP Array_Column

array-column There's a new command in PHP called array_column, that I have been playing with, and like. Just to be ahead of the power curve, I thought I'd do a write up, and give you an overview.

Be aware that the array_column function only works with PHP 5.5 and greater. If you're running below version 5.5.0, not to worry, a developer named Ben Ramsey, (Big Thank You!) wrote the code for earlier PHP versions. I recommend you copy the code on github, here, and add it to your library. For the purposes of this article, I'm using Ben's code.

The array column function works on arrays that are single dimensional to return a filtered array for further processing. The syntax for array_column() is:

$new_array = array_column( "the array to filter", "the column you want in another array", ["an optional associative key"]);

To show off the array_column function, I first want to create a multi-dimensional array for testing.

Here's the code:

$testArr = array(
    array(
        'vin' => '12345FGX',
        'car' => 'Buick',
        'year' => '2004',
        'model' => 'Riviera',
        'owners' => array (
            'original_owner' => 'George Lauren', 
            'date_purchased' => '2003-12-13',
            'owner2' => 'Ralph Plimpton',
            'date_purhcased2' => '2010-08-24',
            'owner3' => 'Gary Redding',
            'date_purchased3' => '2013-09-12'
            ),
    ),
    array(
        'vin' => '2456GHW',
        'car' => 'Ford',
        'year' => '2010',
        'model' => 'Mustang',
        'owners' => array (
            'original_owner' => 'Peter Prunes', 
            'date_purchased' => '2009-12-09',
            ),
    ),
    array(
        'vin' => 'G09RX765',
        'car' => 'Pontiac',
        'year' => '2007',
        'model' => 'LaSabre',
        'owners' => array (
            'original_owner' => 'Fred Forsight', 
            'date_purchased' => '2008-02-15',
            'owner2' => 'Clare Boone',
            'date_purhcased2' => '2010-07-21',
            'owner3' => 'Tony Parker',
            'date_purchased3' => '2014-03-19'
            ),
    ),
    array(
        'vin' => '12345FGX',
        'car' => 'Toyota',
        'year' => '2012',
        'model' => 'Prius',
        'owners' => array (
            'original_owner' => 'Tim Tingle', 
            'date_purchased' => '2011-11-23',
            'owner2' => 'Sally Strumms',
            'date_purhcased2' => '2014-06-15',
            ),
    ));

Notice that the sub_array of owners is not uniform in that some cars have only one owner, and others have more than one owner. .

Using our test array above, let's write some code to pull out the brands of cars, which for example, might represent all the cars for sale at a dealer.

include "../phplib/chk.php";
include "../phplib/array_column.php";
include "testarr.php";

$carsArr = array_column($testArr, 'car', 'vin');

new chk($carsArr);

We start out including my free variable checker, the array_column function we put in our library, and for easier reading and code-simplification, I included the multi-dimensional array we just created. With one line we filter the array and create a separate array of the all the cars. The last line calls my newchk variable checker. Newchk is available for free from a link in the side menu on this blog, and it looks like this:

carsarr660

We used the optional vin number in the array_column call as the associative array key. To get this information before the array_column function, we would have had to use a foreach loop constuct, something like this:

$carsArr = array();
foreach ($testArr as $car) {
   $vinid = $car['vin'];
   $carid = $car['car'];
   $carsArr[$vinid] = $carid;
}

This may seem just as easy, but to me the one line array_column function is a lot simpler, less prone to error, and easier to code.

Let's go a step further. As I mentioned array_column() works with a single dimensional array, but we can use it with a multi-dimension arrays. Suppose we want to collapse the second layer of the multi-dimendional array into its own array.

$ownerArr = array_column($testArr, 'owners');

owner660

Now we can go right back in, and pull the list of original owner's into a separate array, like so:

$ownerArr = array_column($testArr, 'owners');
$origOwnerArr = array_column($ownerArr, 'original_owner');

And now that array looks like this.

origowner660

We take the filtered array, $ownerArr, from the first line, and use it in our array_column call in the second line.

Let's go one step further, get a little fancier, and pull out all the owners into a separate array by using array_merge().

$allOwnersArr = array_merge(
   array_column($ownerArr, 'original_owner'), 
   array_column($ownerArr, 'owner2'), 
   array_column($ownerArr, 'owner3'));

allowners660

Remember that our test array, $testArr, didn't have the same number of owners for each car, and that's not an issue using the array_column function.

If you tried this with a series of foreach loops, things would get a bit more complicated, harder to code, and a lot easier to make mistakes. I'm not going to bother showing you the equivalent layered foreach loops in this example, since array_column works so well. I'll let you do that if you so desire.

The new array_column function is a nice helper function that saves you a lot of time, and coding headaches. As we start installing PHP versions higher than 5.5.0, you'll find this a nice addition to PHP, below that version, I encourage you to drop Ben Ramsey's array_column code into your code library. Enjoy.

Comments

PHP Array_Column — 3 Comments

  1. You mention your free variable checker, the chk.php, but I do not know where to get it. Not sure if it is necessary. Still trying to get a grasp on this function and PHP in general.

    • There is a link to the newchk website in the left sidebar menu of the geekgumbo web site, here’s the url: http://www.newchk.com/

      If your just learning PHP and how to put web pages together, the variable checker may help you visualize what type of variable you have and what it’s set to. The site has documentation on how to use the tool.

      Developer’s who are actively developing web pages and web sites will find the tool much easier to use than any alternatives, such as: print_r, var_dump, echo, print, or the xdebugger.