3

When you convert object with numeric fields (see $obj) to array you can't access it elements

$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 same 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 behaviour? I am using PHP 7.1.2

I discovered thin bug when trying to access JSON elements with numeric 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
Peter
  • 16,453
  • 8
  • 51
  • 77

1 Answers1

2

it is mentioned in the doc that "integer properties are unaccessible" http://php.net/manual/en/language.types.array.php

From the doc

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

Sugumar Venkatesan
  • 4,019
  • 8
  • 46
  • 77