PHP Reference ยท Array Functions
PHP array_column() function
Reference for PHP array_column(): pull one field from every row of a 2D array or object list, re-key the result by another field, or return whole rows.
array_column() takes a list of rows (arrays or objects) and returns the values of one field from each row. It is the quick way to turn "a list of users" into "a list of their email addresses".
You can also choose a second field to use as the keys of the result, which turns a list of records into a lookup table. If a row does not have the requested field, that row is skipped.
<?php $rows = [["id" => 1, "n" => "Ann"], ["id" => 2, "n" => "Bob"]]; print_r(array_column($rows, "n")); // Ann, Bob
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array
| Name | Description |
|---|---|
$array |
A list of arrays or objects. |
$column_key |
The key (or public property name) to extract. null returns the whole row. |
$index_key |
Optional. The key or property whose value becomes the key of each result element. |
Return value: an array of the extracted values, either a list or keyed by $index_key.
Usage notes
- Rows missing the column are skipped, not filled with
null. The result can be shorter than the input. - Duplicate index values overwrite earlier entries, so the last row wins.
- Index values must be usable as array keys (integers or strings). Other types are converted, and rows whose index field is missing are appended with the next numeric key.
- Objects: public properties are read directly; private or protected ones are only reachable if the class implements
__get()and__isset(). nullas the column keeps the whole row, which is the idiom for indexing records by an id.- Not recursive: it only looks at the top level of each row.
- Combine with other functions:
array_sum(array_column(...))totals a field, andarray_combine(array_column(...), array_column(...))is the long form of the keyed version.