Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get one field's values from an array of arrays

Short answer

array_column() collects the values of the given key:

<?php
 
$users = [['id' => 3, 'name' => 'Anna'], ['id' => 5, 'name' => 'Oleg']];
 
echo implode(', ', array_column($users, 'name'));

Output:

Anna, Oleg

With keys

The third argument names the field that becomes the key:

<?php
 
$users = [['id' => 3, 'name' => 'Anna'], ['id' => 5, 'name' => 'Oleg']];
 
echo json_encode(array_column($users, 'name', 'id'));

Output:

{"3":"Anna","5":"Oleg"}

Summing a field

A column is handy to pass straight to array_sum():

<?php
 
$orders = [['total' => 100], ['total' => 250]];
 
echo array_sum(array_column($orders, 'total'));

Output:

350

Functions used in this recipe

  • array_column — Pulls the values of one key out of an array of arrays.
  • array_map — Applies a function to every element of an array.
  • array_combine — Creates an array from two lists: keys and values.

Thanks for reading!

Donate to the site — we work hard for you.