Skip to content
Advertisement

PHP – Extracting a property from an array of objects

I’ve got an array of cats objects:

$cats = Array
    (
        [0] => stdClass Object
            (
                [id] => 15
            ),
        [1] => stdClass Object
            (
                [id] => 18
            ),
        [2] => stdClass Object
            (
                [id] => 23
            )
)

and I want to extract an array of cats’ IDs in 1 line (not a function nor a loop).

I was thinking about using array_walk with create_function but I don’t know how to do it.

Any idea?

Advertisement

Answer

If you have PHP 5.5 or later, the best way is to use the built in function array_column():

$idCats = array_column($cats, 'id');

But the son has to be an array or converted to an array

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement