87

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!

9 Answers 9

94

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


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

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

$key = $objIterator->key(); // and gets the key
Sign up to request clarification or add additional context in comments.

6 Comments

reset() and end() are nice because you don't need to know the key, just the position (first or last).
They should have named reset() like first() or something similar to make more sense. This answer is the correct one. The correct answer does not work.
Moving on to the best practices and OOPS, this answer must be marked as corrected, although my answer provides the solution its not the best method.
Deprecated: reset(): Calling reset() on an object is deprecated
Deprecated: key(): Calling key() on an object is deprecated
|
77

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']

22 Comments

Not really sure about if a documentation explicitly exist for this {} operator. But with experience, I know this is possible. You would be more interested to know that {} operator can be used to iterate through strings as well for eg: $str = "cool"; if you echo $str{0} it will output first letter "C" and echo $str{1} would output "o" and so on.. Give a Try..
With PHP 5.6, this is not possible. You get the following message: Cannot use object of type stdClass as array
No the error is exactly Cannot use object of type stdClass as array which is the error when you try to use a stdClass object as an array. stdClass DOES NOT inherit from base object class, and so doesn't offer this feature.`
Just want to note that this does not work when a object has defined / string key.
@Clain Dsilva: Deal with string "Grzegrzółka"
|
32

much easier:

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

1 Comment

This is great if you don't know the node name.
18

Correct:

$videos= (Array)$videos;
$video = $videos[0];

1 Comment

Good answer, but it's not really helping me navigate through an object, it's just converting it to an array and then navigating it as an array.
8

$videos->{0}->id worked for me.

Since $videos and {0} both are objects, so we have to access id with $videos->{0}->id. The curly braces are required around 0, as omitting the braces will produce a syntax error : unexpected '0', expecting identifier or variable or '{' or '$'.

I'm using PHP 5.4.3.

In my case, neither $videos{0}->id and $videos{0}['id'] worked and shows error :

Cannot use object of type stdClass as array.

Comments

6

You could loop on the object maybe and break in the first loop... Something like

foreach($obj as $prop) {
   $first_prop = $prop;
   break; // exits the foreach loop
} 

Comments

2

Playing with Php interactive shell, Php 7:

➜  ~ php -a
Interactive shell

php > $v = (object) ["toto" => "hello"];
php > var_dump($v);
object(stdClass)#1 (1) {
  ["toto"]=>
  string(5) "hello"
}
php > echo $v{0};
PHP Warning:  Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
Stack trace:
#0 {main}
  thrown in php shell code on line 1

Warning: Uncaught Error: Cannot use object of type stdClass as array in php shell code:1
Stack trace:
#0 {main}
  thrown in php shell code on line 1
php > echo $v->{0};
PHP Notice:  Undefined property: stdClass::$0 in php shell code on line 1

Notice: Undefined property: stdClass::$0 in php shell code on line 1
php > echo current($v);
hello

Only current is working with object.

Comments

0

the following can be done

$rows=null; 
foreach ($result as $rows) break;

Comments

0

The easy and safe solution that nobody mentioned would be

$firstItem = '';
foreach($object as $item) {
  $firstItem = $item;
  break;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.