How can I create an array from the values of another array's key?
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
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.
$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 )