phpobjectmultidimensional-array

Get first element in PHP stdObject


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!


Solution

  • 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 be marked as correct, although my answer provides a hacked solution its not the 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']