PHP stdClass Object how to get element with index 0

I have a stdClass object, for example:

print_r($myobj);

stdClass Object(
[0] => testData
);

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

To get this value, I convert the object to an array, but are there any ways to get without conversion?

+4
source share
2 answers

Try the following:

$obj = new stdClass();

$obj->{0} = 1;

echo $obj->{0};

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

+4
source

So, firstly, although the print_r()conclusion is drawn that the property is literally an integer 0, this is not so. If instead you name var_dump()the object, you will see that it actually looks like this:

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

, 0, PHP $myobject->0? () :

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

, .

0

Source: https://habr.com/ru/post/1621943/


All Articles