The PHP array_column function returns the values from the specified column of an associative array.
Considering the keys as the columns of the associative array, the array_column function is used to get the values of a single column (key) of the array.
What is the syntax of the array_column function?
array_column(array, column_key, index_key)
Parameters | Details |
---|---|
array | Required. Specify the associative array. You can also use objects from PHP 7.0 |
column_key | Required. It can be a string or integer. When it’s an integer it specifies the index of the column to return its values. When it’s a string, it points towards the values of that key. It can also be NULL to reindex an indexed array. |
index_key | Optional. The column to use as the index/keys for the resultant array |
Examples of the array_column function
<?php
// An example array
$arr = array(
array(
'name' => John,
'gender' => 'Male',
'age' => '24',
),
array(
'name' => Peter,
'gender' => 'Male',
'age' => '25',
),
array(
'name' => Tim,
'gender' => 'Female',
'age' => '39',
));
$ages = array_column($arr, 'age', 'name');
print_r($ages);
?>
In the above example, we fetch the column values age column values along with their names.
// Output
Array
(
[John] => 24
[Peter] => 25
[Tim] => 39
)
<?php
// An example array
$arr = array(
array(
'name' => John,
'gender' => 'Male',
'age' => '24',
),
array(
'name' => Peter,
'gender' => 'Male',
'age' => '25',
),
array(
'name' => Tim,
'gender' => 'Female',
'age' => '39',
));
$names = array_column($arr, 'name');
print_r($names);
?>
In the above example, we fetch the names from the array only.
// Output
Array
(
[0] => 24
[1] => 25
[2] => 39
)
For a more in-depth explanation see the official PHP reference.