DisgruntledGoat DisgruntledGoat - 6 months ago 12
PHP Question

How to get object property from each object in an array?

Assuming I have an array of objects in PHP, something like:

Array (
[0] => stdClass Object (
[id] => 1
[name] => Title One
)
[1] => stdClass Object (
[id] => 2
[name] => Title Two
)

[2] => stdClass Object (
[id] => 7
[name] => Title Seven
)
)


What is the best way (i.e. fastest) to get an array of the IDs? i.e.
array(1,2,7)
I can loop manually but I feel there must be a better method.

Just saw this in the similar questions but there's a little debate over whether the accepted answer is really the best way, plus it's from 2 years ago. I'm on PHP 5.3.

Answer

The fastest way is simply looping (foreach, for, while). Using callback functions will incur unnecessary overhead.

I would look to see if there's a way to create the list via the code that is building the initial array of objects.