PHP array_column()
Last Updated: February 9, 2022
If you have an array of records you can get any specified column from the record set. The return data is also in array format.
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
If you want to define the index value of the returned array you can use the index_key
parameter.
Supports (PHP 5 >= 5.5.0, PHP 7, PHP 8)
Parameters
Parameter | Description |
array | Required. Specify the array to be used |
column_key | Required. Column of the value to returned. You can specify the inter key value or string value (in case associative array). If this is null it will return all the elements of the array |
index_key |
Optional: Define the index values of the returned array.This value may be the integer key of the column, or it may be the string key name |
Return Value
array_column() function returns array with single column values
Examples
<?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);
?>
You will get the following values
Array
(
[0] => John
[1] => Sally
[2] => Jane
[3] => Peter
)
Get the column of last_name and index is based on the id column
<?php
$first_names = array_column($records, 'last_name','id);
print_r($first_names);
?>
Output:
Array (
[2135] => John
[3245] => Sally
[5342] => Jane
[5623] => Peter
)