PHP stdClass Object, how to get element with the 0 index [duplicate]
Asked Answered
T

2

6

I have a stdClass Object like this:

print_r($myobj);

stdClass Object(
[0] => testData
);

So it is clear that I cannot get the value by $myobj->0.

For getting this value I convert the object to an array, but are there any ways to get without converting?

Trefoil answered 28/12, 2015 at 10:49 Comment(1)
you can do it using echo $myobj->{0};Tonne
F
6

Try this:

$obj = new stdClass();

$obj->{0} = 1;

echo $obj->{0};

source: http://php.net/manual/en/language.types.object.php

Flushing answered 28/12, 2015 at 10:57 Comment(0)
T
0

So firstly, even though it appears from print_r()'s output that the property is literally integer 0, it is not. If you call var_dump() on the object instead, you'll see that, in fact, it looks like this:

php > var_dump($myobject);
object(stdClass)#2 (1) {
  ["0"]=>
  string(4) "testData"
}

So how do you access a property named 0 when PHP won't let you access $myobject->0? Use the special Complex (curly) syntax:

php > echo $myobject->{0};
test
php > echo $myobject->{'0'};
test
php >

You can use this method to access property names that are not considered valid syntax.

Turtleback answered 28/12, 2015 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.