array_column
Pulls the values of one key out of an array of arrays.
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | An array of rows or objects. |
| $column_key | int|string|null | The key whose values to collect. |
| $index_key | int|string|null | Optional. The key whose values become the keys of the result. |
Return value
arrayAn array of the values.
Examples
A list of names:
<?php
$users = [['id' => 3, 'name' => 'Anna'], ['id' => 5, 'name' => 'Oleg']];
echo implode(', ', array_column($users, 'name'));Output:
Anna, OlegNames keyed by identifier:
<?php
$users = [['id' => 3, 'name' => 'Anna'], ['id' => 5, 'name' => 'Oleg']];
echo json_encode(array_column($users, 'name', 'id'));Output:
{"3":"Anna","5":"Oleg"}Notes
Handy for a database result set: one line instead of a loop.
See also
- array_map — Applies a function to every element of an array.
- array_combine — Creates an array from two lists: keys and values.
Related recipes
In the tutorial
- Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.