Array_values ββfrom multidimensional array
The array looks like
$arr = array(
array('a', 'b'),
array('c', 'd'),
array('e', 'f'),
)
And I want to get an array with values ββfrom the first column like array('a', 'c', 'e')
I know this can be easily done by iterating over an array and storing the values ββin another array, but is there a shorter way, a built-in PHP function or something?
+3
source to share
4 answers
Since PHP 5.5, you can use array_column()
:
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe'
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith'
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones'
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe'
)
);
$lastNames = array_column($records, 'last_name', 'id');
print_r($lastNames);
Array
(
[2135] => Doe
[3245] => Smith
[5342] => Jones
[5623] => Doe
)
+9
source to share
You can do:
$foo = array_map('reset', $arr);
Anyone reading your code after this should know that the reset side effect returns the first value in the array. It may or may not be more readable - and it has the disadvantage that it doesn't work unless the array has a zero-indexed entry:
$baz = array_map(function ($a) { return $a[0]; }, $arr);
If you want to be very clear and don't mind having a function lying around:
function array_first($a) {
return reset($a);
}
$baz = array_map('array_first', $arr);
+6
source to share