73

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!

Drew Baker
  • 13,308
  • 12
  • 50
  • 90

7 Answers7

79

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

MrTrick
  • 1,797
  • 11
  • 11
  • reset() and end() are nice because you don't need to know the key, just the position (first or last). – jonathanbell Dec 24 '16 at 16:21
  • 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. – Andres Ramos Nov 03 '17 at 17:02
  • 1
    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. – Clain Dsilva Feb 10 '19 at 13:35
72

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']
cocostru
  • 160
  • 2
  • 9
Clain Dsilva
  • 1,564
  • 2
  • 23
  • 33
  • 4
    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.. – Clain Dsilva Jan 24 '14 at 08:30
  • 4
    With PHP 5.6, this is not possible. You get the following message: Cannot use object of type stdClass as array – Dereckson Nov 20 '14 at 04:19
  • @Dereckson { } works perfectly fine with PHP 5.6 with a little change in syntax by removing -> and using ['objectName']. The final code will be `$videos{0}['id']` . Php 5.4+ gives mores emphasis on objects hence -> may not work because {0} is already referencing the object. – Clain Dsilva Nov 21 '14 at 06:08
  • I'm sorry for the lack of precision in the previous comment. The fatal error is thrown when using the {0} on an object under PHP 5.6.2, not the ->id. – Dereckson Nov 21 '14 at 15:31
  • @Dereckson probably you are getting an error like this `Trying to get the property of a non object` as {0} still referees to a node on the object. While an identifier ->elementName or ['elementName'] is a must. – Clain Dsilva Nov 25 '14 at 09:37
  • 1
    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.` – Dereckson Nov 25 '14 at 14:44
  • @Dereckson Interesting to know, probably you should post you code on here on stack overflow, we could take a look into it, perhaps we have a solution for it. – Clain Dsilva Nov 26 '14 at 15:43
  • I spoke about the OP code. The solution is to use every other answer on this page, which all work. – Dereckson Nov 27 '14 at 20:24
  • @Dereckson knowing why a code does not works helps us to fix the issues and provide even more better answers. I guess you got my point , you are welcome to use any answer that works. – Clain Dsilva Nov 28 '14 at 12:54
  • it doesn't work on recent PHP versions as you have answered to another question. Instead of "in stdObject", you considered "in any object [inheriting of base object class]". Yet, stdObject isn't such an object in PHP, as it doesn't inherit from the base object class. – Dereckson Nov 28 '14 at 19:09
  • @Dereckson I am confused, wonder how you use the class directly without inheriting 0r creating an object? Its worth giving you code here on a new question – Clain Dsilva Nov 29 '14 at 04:41
  • @Dereckson on an other note this works fine on the latest version tested with PHP 5.6 and works great. – Clain Dsilva Nov 29 '14 at 04:49
  • @sure off course I can, please post your stdObject code we can take it from there. – Clain Dsilva Dec 01 '14 at 08:16
  • My method of accessing the child object was `$videos->{0}` or `$videos->{0}->id` in PHP 5.6.7. I couldn't see this mentioned here. – Francis Booth Jun 12 '15 at 21:50
  • 1
    Just want to note that this does not work when a object has defined / string key. – MKN Web Solutions Mar 10 '16 at 20:23
  • @MKNWebSolutions even a defined sting or Key has an internal numeric key hence this works.. Or can you provide us with an example? – Clain Dsilva Mar 16 '16 at 07:06
  • @ClainDsilva stdObject as $x = {"xyz":123}, using $x->{0} would not return that first element. – MKN Web Solutions Mar 16 '16 at 16:44
  • @MKNWebSolutions you are talking about stdClass which is not our point of discussion we are talking about the base class, PHP differs a lot in Standard Class and Base class.. You should read this to get more insights http://stackoverflow.com/questions/931407/what-is-stdclass-in-php – Clain Dsilva Mar 19 '16 at 03:24
  • @Clain Dsilva: You're wrong. You cannot iterate over the letters but bytes. It's totally different. – John Smith Apr 28 '16 at 20:49
  • @JohnSmith Prove me wrong or try this yourself `$str = "Its Possible"; for($i = 0; $i < strlen($str); $i++) { echo $str{$i}."
    ";}`
    – Clain Dsilva Apr 30 '16 at 11:03
  • 2
    @Clain Dsilva: Deal with string "Grzegrzółka" – John Smith Apr 30 '16 at 19:39
  • @JohnSmith I see your point on multi byte Unicode chars , so its bytes and not characters... Thanks for proving me wrong..!! I learned something new today. – Clain Dsilva May 03 '16 at 07:44
22

much easier:

$firstProp = current( (Array)$object );
Mureinik
  • 252,575
  • 45
  • 248
  • 283
Patrick
  • 221
  • 2
  • 2
17

Correct:

$videos= (Array)$videos;
$video = $videos[0];
Ben D
  • 13,146
  • 3
  • 43
  • 59
froilanq
  • 894
  • 7
  • 8
  • 5
    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. – Drew Baker Dec 13 '12 at 00:43
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.

Biraj Bora
  • 829
  • 2
  • 12
  • 23
5

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
} 
Rolf
  • 4,872
  • 4
  • 36
  • 52
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.

Thomas Decaux
  • 18,451
  • 2
  • 83
  • 95