Cannot access array element using numeric associative key when converting from object
When you convert an object with numeric fields (see $obj
) to an array, you cannot get elements to it
$obj = new stdClass();
$obj->{"325890"} = "test";
$arr = (Array) $obj;
$key = array_keys($arr)[0];
var_dump($arr); // array (size=1) '325890' => string 'test' (length=4)
var_dump($key); // string '325890' (length=6)
var_dump($arr["325890"]); // null
var_dump($arr[325890]); // null
var_dump($arr[$key]); // null
$arr = unserialize(serialize($arr)); // this fixes that
var_dump($arr["325890"]); // string 'test' (length=4);
Also, something strange happens when you assign data to a single element:
$arr = (Array) $obj;
$arr[325890] = "test"; // or $arr["325890"] = "test";
var_dump($arr);
array (size = 2)
'325890' => string 'test' (length = 4)
325890 => string 'test' (length = 4)
Is this a bug or documented behavior? I am using PHP 7.1.2
I ran into a subtle error while trying to access JSON elements using number keys.
$items = Array(
"100" => "item",
"200" => "item",
"300" => "item",
"400" => "item",
);
$json = json_encode($items);
$items = (Array) json_decode($json);
var_dump($items[100]); // null
source to share
the doc states that "integer properties are not available" http://php.net/manual/en/language.types.array.php
From doc
If an object is converted to an array, the result is an array whose elements are the properties of the object. Keys are the names of member variables, with a few notable exceptions: integer properties are not available; private variables have a class name appended to the variable name; protected variables have "*" appended to the variable name. These preliminary values have zero bytes on either side. This can lead to unexpected behavior:
source to share