array_column

(PHP 5 >= 5.5.0)

array_columnReturn the values from a single column in the input array

Descrierea

array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )

array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

Parametri

array

A multi-dimensional array (record set) from which to pull a column of values.

column_key

The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array. It may also be NULL to return complete arrays (useful together with index_key to reindex the array).

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.

Valorile întoarse

Returns an array of values representing a single column from the input array.

Exemple

Example #1 Get column of first names from recordset

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        
'id' => 2135,
        
'first_name' => 'John',
        
'last_name' => 'Doe',
    ),
    array(
        
'id' => 3245,
        
'first_name' => 'Sally',
        
'last_name' => 'Smith',
    ),
    array(
        
'id' => 5342,
        
'first_name' => 'Jane',
        
'last_name' => 'Jones',
    ),
    array(
        
'id' => 5623,
        
'first_name' => 'Peter',
        
'last_name' => 'Doe',
    )
);
 
$first_names array_column($records'first_name');
print_r($first_names);
?>

Exemplul de mai sus va afișa:

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Example #2 Get column of last names from recordset, indexed by the "id" column

<?php
// Using the $records array from Example #1
$last_names array_column($records'last_name''id');
print_r($last_names);
?>

Exemplul de mai sus va afișa:

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

add a note add a note

User Contributed Notes 6 notes

up
69
fireweasel@wirefeasel
9 months ago
Please, don't invent your own implementation of array_column(). The author of this function already provides a version written in plain PHP:

https://github.com/ramsey/array_column

See also:

http://benramsey.com/blog/2013/07/the-array-column-php-userland-library/
up
1
jakubplus at gmail dot com
13 days ago
This is somehow different from other approaches to satisfy needs of those not having a pleasure to deal with PHP 5.

I've minimized need of using loops, so I use only one, to grab the whole array. Works fine with additional parameter for returned key, empty or unelegant arrays:

$arr = array(
    'director' => array(
        'id' => 1,
        'firstname' => 'Markus',
        'lastname' => 'Tambis',
        'age' => 43,
        'height' => 180
    ),
    'merchandise' => array(
        'id' => 602,
        'firstname' => 'Ronald',
        'lastname' => 'Plus',
        'age' => 43,
        'height' => 180,
        'city' => 'Berlin'
    ),
    'sales' => array(
        'id' => 55,
        'firstname' => 'Veronica',
        'lastname' => 'Ambit',
        'city' => 'Warsaw'
    ),
    array(
        'id' => 4,
        'firstname' => 'Trevor',
        'lastname' => 'Howard',
        'middlename' => 'Prover'
    ),
    'anna'
);

function array_column(array $array, $returnvaluekey = null, $returnkey = null) {
    if($returnvaluekey===null) {
        return false;
    }
    $columns = array();
    foreach($array as $key=>$value) {
        if(!is_array($array[$key]) || empty($array[$key])) {
            continue;
        }
        if($returnkey===null) {
            if(isset($array[$key][$returnvaluekey])) {
                $columns[] = $array[$key][$returnvaluekey];
            }
        }
        else {
            if(isset($array[$key][$returnkey]) && isset($array[$key][$returnvaluekey])) {
                $columns[$array[$key][$returnkey]] = $array[$key][$returnvaluekey];
            }
        }
    }
    return $columns;
}
print_r(array_column($arr, 'middlename', 'firstname')); ...prints:

Array ( [Trevor] => Prover )
up
2
vovan-ve at yandex dot ru
11 months ago
>>> for < PHP5.5 , following function can be used :

NEVER edit items of array argument by reference! It WILL damage items of original array, which are referenced outside with another variables like this:

    $foo = array(10, 20, 30);
    $bar = &$foo[1];

You should just to collect a new array instead of changing array by reference.
So, userland implementation can be such a following:

    # PHP < 5.5
    function array_column(array $input, $columnKey, $indexKey = null) {
        $result = array();
   
        if (null === $indexKey) {
            if (null === $columnKey) {
                // trigger_error('What are you doing? Use array_values() instead!', E_USER_NOTICE);
                $result = array_values($input);
            }
            else {
                foreach ($input as $row) {
                    $result[] = $row[$columnKey];
                }
            }
        }
        else {
            if (null === $columnKey) {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row;
                }
            }
            else {
                foreach ($input as $row) {
                    $result[$row[$indexKey]] = $row[$columnKey];
                }
            }
        }
   
        return $result;
    }
up
0
WARrior
6 months ago
You can also use array_map fucntion if you haven't array_column().

example:

$a = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    )
);

array_column($a, 'last_name');

becomes

array_map(function($element){return $element['last_name']}, $a)
up
-6
ohcc at 163 dot com
4 months ago
This function will fail when you try to fetch columns from an indexed array.

<?php
    $a
=array(
            array(
1,2,3),
            array(
4,5,6),
            array(
7,8,9)
    );
   
print_r(array_column($a,'0'));
?>
Expected results should be :
Array
(
    [0] => 1
    [1] => 4
    [2] => 7
)
But we get :
Array (
)

Instead I have create another function.

<?php
   
function my_array_column($array,$colName){
       
$results=array();
        if(!
is_array($array)) return $results;
        foreach(
$array as $child){
            if(!
is_array($child)) continue;
            if(
array_key_exists($colName,$child)){
               
$results[] = $child[$colName];
            }
        }
        return
$results;
    }

   
$a =array(
            array(
1,2,3),
            array(
4,5,6),
            array(
7,8,9)
    );
   
print_r(my_array_column($a,'0'));   
?>

Now we get the right results:

Array
(
    [0] => 1
    [1] => 4
    [2] => 7
)
up
-11
jan venekamp
9 months ago
Implementation for PHP < 5.5.0
Following: https://wiki.php.net/rfc/array_column

<?php
// PHP < 5.5.0
if (!function_exists('array_column')) {
    function
array_column($input, $column_key, $index_key = null)
    {
        if (
$index_key !== null) {
           
// Collect the keys
           
$keys = array();
           
$i = 0; // Counter for numerical keys when key does not exist
           
           
foreach ($input as $row) {
                if (
array_key_exists($index_key, $row)) {
                   
// Update counter for numerical keys
                   
if (is_numeric($row[$index_key]) || is_bool($row[$index_key])) {
                       
$i = max($i, (int) $row[$index_key] + 1);
                    }
                   
                   
// Get the key from a single column of the array
                   
$keys[] = $row[$index_key];
                } else {
                   
// The key does not exist, use numerical indexing
                   
$keys[] = $i++;
                }
            }
        }
       
        if (
$column_key !== null) {
           
// Collect the values
           
$values = array();
           
$i = 0; // Counter for removing keys
           
           
foreach ($input as $row) {
                if (
array_key_exists($column_key, $row)) {
                   
// Get the values from a single column of the input array
                   
$values[] = $row[$column_key];
                   
$i++;
                } elseif (isset(
$keys)) {
                   
// Values does not exist, also drop the key for it
                   
array_splice($keys, $i, 1);
                }
            }
        } else {
           
// Get the full arrays
           
$values = array_values($input);
        }
       
        if (
$index_key !== null) {
            return
array_combine($keys, $values);
        }
       
        return
$values;
    }
}

?>
To Top