How can I create an array from the values of another array's key?

newbtophp picture newbtophp · Dec 29, 2010 · Viewed 44.1k times · Source

I have an array as follows:

$arr1 = array(
  0 => array(
    'name' => 'tom',
    'age' => 22
  ),
  1 => array(
    'name' => 'nick',
    'age' => 18
  )
);

However I want to create an array from it which consists of all the names, so it would become:

$arr2 = array('tom', 'nick');

I have looked at array_filter(), but that would not work as this is a multi-dimensional array!

Question

How can I create an array with the values of a specific key (name) from another multi-dimensional array?

Answer

jwueller picture jwueller · Dec 29, 2010

Newer versions of PHP allow using array_map() with a function expression instead of a function name:

$arr2 = array_map(function($person) {
    return $person['name'];
}, $arr1);

But if you are using a PHP < 5.3, it is much easier to use a simple loop, since array_map() would require to define a (probably global) function for this simple operation.

$arr2 = array();

foreach ($arr1 as $person) {
    $arr2[] = $person['name'];
}

// $arr2 now contains all names