Is there a function to extract a 'column' from an array in PHP?

Here's a functional way of doing it:

$data = array(
            array('page' => 'page1', 'name' => 'pagename1'),
            array('page' => 'page2', 'name' => 'pagename2'),
            array('page' => 'page3', 'name' => 'pagename3'));

$result = array_map(create_function('$arr', 'return $arr["name"];'), $data);
print_r($result);

As of PHP 5.5 you can use array_column():

<?php
$samples=array(
            array('page' => 'page1', 'name' => 'pagename1'),
            array('page' => 'page2', 'name' => 'pagename2'),
            array('page' => 'page3', 'name' => 'pagename3')
            );
$names = array_column($samples, 'name');
print_r($names);

See it in action


Why does it have to be a built in function? No, there is none, write your own.

Here is a nice and easy one, as opposed to others in this thread.

$namearray = array();

foreach ($array as $item) {
    $namearray[] = $item['name'];
}

In some cases where the keys aren't named you could instead do something like this

$namearray = array();

foreach ($array as $key => $value) {
    $namearray [] = $value;
}

Well there is. At least for PHP > 5.5.0 and it is called array_column

The PHP function takes an optional $index_keyparameter that - as per the PHP website - states:

$index_key

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name

In the answers here, i see a stripped version without the optional parameter. I needed it, so, here is the complete function:

if (!function_exists('array_column')) {
    function array_column($array, $column, $index_key = null) {
        $toret = array();
        foreach ($array as $key => $value) {
            if ($index_key === null){
                $toret[] = $value[$column];
            }else{
                $toret[$value[$index_key]] = $value[$column];
            }
        }
        return $toret;
    }
}

Tags:

Php

Arrays