PHP array_column()Function

PHP Array 参考手册Complete PHP Array Reference Manual

Examples

Get the last_name column from the record set:

<?php
// An array that may be returned from the database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name');
print_r($last_names);
?>

Output:

Array
(
  [0] => Griffin
  [1] => Smith
  [2] => Doe
)


Definition and Usage

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


Syntax

array_column(array,column_key,index_key);

Parameters Description
array Required. Specifies the multidimensional array (record set) to use.
column_key Required. The column whose value needs to be returned. It can be the integer index of a column in an indexed array, or the string key of a column in an associative array. This parameter can also be NULL, in which case the entire array will be returned (this is very useful when combined with the index_key parameter to reset array keys).
index_key Optional. The column to use as the index/key of the returned array.

Technical Details

Return value: Returns an array with the values of a single column from the input array.
PHP Version: 5.5+


More Examples

Example 1

Get the last_name column from the record set, using the corresponding "id" column as keys:

<?php
// An array that may be returned from the database
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Peter',
    'last_name' => 'Griffin',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Ben',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Joe',
    'last_name' => 'Doe',
  )
);

$last_names = array_column($a, 'last_name', 'id');
print_r($last_names);
?>

Output:

Array
(
  [5698] => Griffin
  [4767] => Smith
  [3809] => Doe
)



PHP Array 参考手册Complete PHP Array Reference Manual Other Extensions