27

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?

0

4 Answers 4

52

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
Sign up to request clarification or add additional context in comments.

5 Comments

It is still efficient to create a global function than a complex loop.
@Christian Sciberras: True, but it pollutes the namespace with unneeded micro-functions. The loop is not that complex here. It is a quite simple iteration (assuming that the initial array does not contain massive loads of data).
Actually, for .. each is quicker. Tested it and it seems 2 - 3x faster. Couldn't tell you why though....
both array_map and foreach() are O(n), but the array_map call has to build the function and call it for reach item in the array, in addition to doing the actual iteration. The foreach() loop doesn't have the function overhead, so it's faster. array_map should only really be used if you're doing something complicated with each item in the array. It's overkill for this particular problem.
Nathan describes it perfectly, the exact same reason I said "complex loop" (which is not the case here). +1
30

This can be done in still more simple way by using array_column

$arr2= array_column($arr1, 'name');

print_r($arr2); //Array ( [0] => tom [1] => nick )

array_column is used to get the columns of a sub-array.

Comments

3
$array = array(0 => array('name' => 'tom', 'age' => 22), 1 => array('name' => 'nick', 'age' => 18));
foreach($array as $arr => $a){
    $names[] = $array[$arr]["name"];
}

print_r($names); //Array ( [0] => tom [1] => nick ) 

Comments

-2

if you are using Laravel, then simply use array_pluck:

$arr2 = array_pluck($arr1 , 'name');

3 Comments

This doesn't seem to be a standard PHP function. array_column can be used instead.
Thanks for your note. I use array_pluck in Laravel. I have updated my answer.
I am using laravel but still does not have array_pluck. Do you need to add an extension also? Btw array_coloumn worked as expected

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.