The PHP array_column() function returns the values from a single column of a multidimensional array. You can also provide an optional index column to use as the keys in the result.
Version Support: array_column() in PHP 8.5, array_column() in PHP 8.4, array_column() in PHP 8.3, array_column() in PHP 8.2, array_column() in PHP 8.1, array_column() in PHP 7.1, array_column() in PHP 7.2, array_column() in PHP 7.3, array_column() in PHP 7.4
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
- $array — The input array.
- $column_key — The key or property to retrieve from each item.
- $index_key (optional) — The key or property to use as the result’s array keys.
Basic example
<?php
$users = [
[ id => 1, name => Ava ],
[ id => 2, name => Noah ],
];
$names = array_column($users, name );
print_r($names);
?>
Output:
Array
(
[0] => Ava
[1] => Noah
)
Use another column as the result keys
<?php
$namesById = array_column($users, name , id );
print_r($namesById);
?>
Output:
Array
(
[1] => Ava
[2] => Noah
)