Get first element in PHP stdObject

Drew Baker picture Drew Baker · Feb 28, 2012 · Viewed 102.1k times · Source

I have an object (stored as $videos) that looks like this

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

  etc...

I want to get the ID of just that first element, without having to loop over it.

If it were an array, I would do this:

$videos[0]['id']

It used to work as this:

$videos[0]->id

But now I get an error "Cannot use object of type stdClass as array..." on the line shown above. Possibly due to a PHP upgrade.

So how do I get to that first ID without looping? Is it possible?

Thanks!

Answer

MrTrick picture MrTrick · Aug 30, 2013

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