Converting to an array does not help. PHP has the nasty habit of creating an inaccessible array element if you try:
- The object property name is always a string, even if it is a digit.
- Converting that object to an array will keep all property names as new array keys - this also applies to strings with only numbers.
- 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!