The decision depends on the version of PHP you are using. At least there are two solutions:
First (newer versions of PHP)
As @JosepAlsina said before the best as well as the shortest solution, you should use array_column as follows:
$catIds = array_column($objects, 'id');
Note: For iterating an array containing \stdClass es, as used in the question, it is only possible with PHP versions >= 7.0 . But when using an array containing array , you can do the same with PHP >= 5.5 .
Second (older versions of PHP)
@Greg said in older versions of PHP that you can do the following:
$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
But be careful: in newer versions of PHP >= 5.3.0 it is better to use Closure s, for example follow:
$catIds = array_map(function($o) { return $o->id; }, $objects);
Difference
The first solution creates a new function and puts it in your RAM. For some reason, the garbage collector does not delete the already created and already called function instance from memory. And the next time this code is called, the same function will be created again. This behavior slowly fills your memory ...
Both examples with memory output for comparison:
Bad
while (true) { $objects = array_map(create_function('$o', 'return $o->id;'), $objects); echo memory_get_usage() . "\n"; sleep(1); } 4235616 4236600 4237560 4238520 ...
GOOD ONES
while (true) { $objects = array_map(function($o) { return $o->id; }, $objects); echo memory_get_usage() . "\n"; sleep(1); } 4235136 4235168 4235168 4235168 ...
It can also be discussed here.
Memory leak?! Is the garbage collector correct using 'create_function' in 'array_map'?