Get first element in PHP stdObject Get first element in PHP stdObject php php

Get first element in PHP stdObject


Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {  [0]=>  object(stdClass)#20 (22) {    ["id"]=>    string(1) "123"  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element$key = key($obj);

Hope that works for you. :-)No errors, even in super-strict mode, on PHP 5.4


Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must bemarked as correct, although my answer provides a hacked solution its notthe best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']


much easier:

$firstProp = current( (Array)$object );