I am converting from JSON to object and from object to array. It does not what I expected, can you explain to me?
$json = '{"0" : "a"}';
$obj = json_decode($json);
$a = (array) $obj;
print_r($a);
echo("a0:".$a["0"]."<br>");
$b = array("0" => "b");
print_r($b);
echo("b0:".$b["0"]."<br>");
The output here is:
Array ( [0] => a ) a0:
Array ( [0] => b ) b0:b
I would have expected a0:a at the end of the first line.
Edit: After reading the answers I extended the code, which makes the behaviour more clear:
//extended example
$json = '{"0" : "a"}';
$obj = json_decode($json);
$a = (array) $obj;
var_export($a);
echo("a0:".$a["0"]."<br>"); //this line does not work, see the answers
echo $obj->{"0"}."<br>"; //works!
$json = '{"x" : "b"}';
$obj = json_decode($json);
$b = (array) $obj;
var_export($b);
echo("bx:".$b["x"]."<br>");
$c = array("1" => "c");
var_export($c);
echo("c1:".$c["1"]."<br>");
$d = array("0" => "d");
var_export($d);
echo("d0:".$d["0"]."<br>");
Output of extended example:
array ( '0' => 'a', )a0:
a
array ( 'x' => 'b', )bx:b
array ( 1 => 'c', )c1:c
array ( 0 => 'd', )d0:d
There’s more information in this older question. The short version is that properties on PHP objects/classes follow the same naming convention as variables. A numerical property is invalid on a PHP object, so there’s no clear rule as to what should happen when serializing an object from another language (json/javascript) that has a numerical key. While it seems obvious to you what should happen with the above, someone with a different bias sees PHP’s behavior in this instance as perfectly valid and preferred.
So, it’s kind of a bug, but more an undefined area of the spec with no clear answer, so don’t expect the behavior to change to meet your liking, and if it does change, don’t expect that change to be permanent.
To address some of the issues in the comments, consider this
that will output something like this
An array with a single string key zero isn’t a valid PHP construct. If you try to create one PHP will turn the zero into an int for you. When you ask PHP to do a cast it doesn’t have a definition for, it ends up creating an array with a string key (because of the ill defined rules around what should happen here).
While it’s blatantly obvious that this is "wrong" behavior on the part of PHP, defining the right behavior in a language that’s weakly typed isn’t easy.