PHP 8 reference · Array Functions
PHP array_column() Function
Return the values from one column of a list of records, optionally keyed by another column.
PHP 8 Since 5.5
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
Parameters
| Parameter | Description |
|---|---|
array |
A list of arrays or objects (rows). |
column_key |
The column to return; null returns whole rows. |
index_key optional |
A column to use as the keys of the result. |
Return value
An array of the column's values.
Examples
<?php
$users = [
["id" => 3, "name" => "Ada", "role" => "admin"],
["id" => 7, "name" => "Alan", "role" => "editor"],
];
print_r(array_column($users, "name"));
print_r(array_column($users, "role", "name"));
Output
Array
(
[0] => Ada
[1] => Alan
)
Array
(
[Ada] => admin
[Alan] => editor
)<?php
$rows = [["id" => 3, "name" => "Ada"], ["id" => 7, "name" => "Alan"]];
$byId = array_column($rows, null, "id");
echo $byId[7]["name"], "\n";
Output
Alan
Version history
| Version | Change |
|---|---|
| PHP 5.5 | Added |
| PHP 7.0 | Works with arrays of objects (public properties). |
Related
array_map()· Apply a callback to every element of one or more arrays and return a new array of the results.array_combine()· Create an array by using one array for keys and another for values. Both arrays must have the same number of elements.usort()· Sort an array's values with your own comparison function, in place. Keys are discarded. Use <=> for easy comparisons.- PHP Array Functions · tutorial
- PHP Arrays · tutorial