0

Please, help to solve the problem

stdClass Object
(
    [0] => stdClass Object
        (
            [value] => 1
        )

)

How can I get access to element [0]? I tried convert to array:

$array = (array)$obj;
var_dump($array["0"]);

but as a result I get NULL.

asuran
  • 3
  • 2

2 Answers2

2

Converting to an array does not help. PHP has the nasty habit of creating an inaccessible array element if you try:

  1. The object property name is always a string, even if it is a digit.
  2. Converting that object to an array will keep all property names as new array keys - this also applies to strings with only numbers.
  3. Trying to use the string "0" as an array index will be converted by PHP to an integer, and an integer key does not exist in the array.

Some test code:

$o = new stdClass();
$p = "0";
$o->$p = "foo";

print_r($o); // This will hide the true nature of the property name!
var_dump($o); // This reveals it! 

$a = (array) $o; 
var_dump($a); // Converting to an array also shows the string array index.

echo $a[$p]; // This will trigger a notice and output NULL. The string 
             // variable $p is converted to an INT

echo $o->{"0"}; // This works with the original object. 

Output created by this script:

stdClass Object
(
[0] => foo
)
class stdClass#1 (1) {
public $0 =>
string(3) "foo"
}
array(1) {
'0' =>
string(3) "foo"
}

Notice: Undefined index: 0 in ...


foo

Praise @MarcB because he got it right in the comments first!

Sven
  • 69,403
  • 10
  • 107
  • 109
0
$array = (array)$obj;
var_dump($array[0]);
Ollie Strevel
  • 861
  • 1
  • 14
  • 27
  • "...I tried convert to array: `$array = (array)$obj; var_dump($array["0"]);` but as a result I get NULL." --OP – cHao Aug 09 '13 at 17:46
  • How do you get this output? – Ollie Strevel Aug 09 '13 at 17:56
  • @brbcoding: Try it with `json_decode('{"0":{"value":1}}')`. Converting an array to an object and back does the right thing, because PHP knows how to do that correctly...but `json_decode` is rather dim-witted, and creates objects with numeric-string (rather than integer) keys. – cHao Aug 09 '13 at 18:01
  • @brbcoding: You are incorrectly creating the initial state. That's why it works. – Sven Aug 09 '13 at 18:02