Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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): array

Parameters

ParameterTypeDescription
$arrayarrayAn array of rows or objects.
$column_keyint|string|nullThe key whose values to collect.
$index_keyint|string|nullOptional. 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, Oleg

Names 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.

Thanks for reading!

Donate to the site — we work hard for you.