How to Use the PHP array_column() Function

09/09/2021
Contents
In this article, you will learn how to use the PHP array_column() Function.
PHP array_column() Function
The array_column() function is a PHP function used to return the values from a single column of an input array.
Syntax:
array_column(array $input, mixed $column_key [, mixed $index_key = null ]) : array
Parameters:
$input
: The input array to be processed.$column_key
: The column key to be used to index the values in the input array.$index_key
(optional): The column key to be used to index the keys of the returned array.
Example:
<?php
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3244,
'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);
// Output:
// Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )
?>
You can also specify the $index_key to index the returned array by a specific column:
<?php
$first_names = array_column($records, 'first_name', 'id');
print_r($first_names);
// Output:
// Array ( [2135] => John [3244] => Sally [5342] => Jane [5623] => Peter )
?>