Let’s assume I have the following multidimensional array (retrieved from MySQL or a service):
array(
array(
[id] => xxx,
[name] => blah
),
array(
[id] => yyy,
[name] => blahblah
),
array(
[id] => zzz,
[name] => blahblahblah
),
)
Can we get an array of ids in one “built-in” php function call? or one line of code?
I am aware of the traditional looping and getting the value but I don’t need this:
foreach($users as $user) {
$ids[] = $user['id'];
}
print_r($ids);
Maybe some array_map() and call_user_func_array() can do the magic.
Since PHP 5.5, you can use
array_column:This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use
array_mapwith an anonymous function, like this:Before (Technically PHP 4.0.6+), you must create an anonymous function with
create_functioninstead: