PHP array_column() Function

Example

Extract the 'last_name' column from the record set:

<?php
// Indicates the array of possible records returned by the database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Bill',
    'last_name' => 'Gates',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Steve',
    'last_name' => 'Jobs',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Mark',
    'last_name' => 'Zuckerberg',
  )
);
$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

Output:

Array
(
  [0] => Gates
  [1] => Jobs
  [2] => Zuckerberg
)

Definition and Usage

array_column() returns the values of a single column from the input array.

Syntax

array_column(array,column_key,index_key);
Parameter Description
array Mandatory. Specifies the multidimensional array (record set) to be used.
column_key

Required. The column that needs to return the value.

It can be an integer index of the column of an indexed array, or a string key value of the column of an associative array.

This parameter can also be NULL, in which case the entire array will be returned (very useful when resetting the array keys with the index_key parameter).

index_key Optional. Used as the index/key of the returned array.

Technical Details

Return Value: Returns an array, the values of which are the values of a single column in the input array.
PHP Version: 5.5+

More Examples

Example 1

Extract the 'last_name' column from the record set, using the corresponding 'id' column as the key value:

<?php
// Indicates the array of possible records returned by the database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Bill',
    'last_name' => 'Gates',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Steve',
    'last_name' => 'Jobs',
  )
  array(
    'id' => 3809,
    'first_name' => 'Mark',
    'last_name' => 'Zuckerberg',
  )
);
$last_names = array_column($a, 'last_name', 'id');
print_r($last_names);
?>

Output:

Array
(
  [5698] => Gates
  [4767] => Jobs
  [3809] => Zuckerberg
)