Access an object as an array in PHP

Have you ever been in that position when you are working with an PHP object and you need only one single peace of the data it contains and you want to skip all that iteration part and access that data directly. I have.

It is very easy to do in an array by using the index or the key as it is usually called. So to access the first item of an array in PHP without iterating over it you would do something like this:

echo $array[0]

It gets more complicated with nested arrays:

echo $array[0][0] //Numbered Indexs

echo $array['item']['subitem'] //String Indexes

echo $array[0]['item'] //Mixed Indexes

But we have an object to access, right? And the good news is we can do it with an object too. Here is my favourite way of doing it with an object:

$object->{'0'}->item

Or you can cast the type from an object to an array like this:

$array = (array) $object;
$array[0]->item;

But this feels kind of hack-ish and I’ve not heard good words about this method. Since the first method is pretty neat, I suggest you go with that.

This is it for this post. Until next time, stay blessed!

You may also enjoy…