1

I know that it's better to call json_decode with second argument as true if I want to have JSON as array, but PHP allows typecasting stdClass to array, and then this issue happens:

<?php
$array = (array) json_decode('{"1":"1","2":"1","3":"1","4":"1","12":"1"}');
var_dump($array);
var_dump(array_key_exists('12', $array));

And result will be:

array(5) {
  ["1"]=>
  string(1) "1"
  ["2"]=>
  string(1) "1"
  ["3"]=>
  string(1) "1"
  ["4"]=>
  string(1) "1"
  ["12"]=>
  string(1) "1"
}
bool(false)

Also, when I try to make:

$array['12'] = 'X';

'12' will be typecasted to INT, so I will have keys 12 and '12' in array when var_dumping. Anybody know why?


Please don't say that I need to use json_decode(..., true) - I really know and understand this, I just want to know what happens under the hood here, to better understand how PHP works and why I should(not) avoid typecasting objects to arrays.

gnysek
  • 319
  • 1
  • 15

1 Answers1

0

Numeric keys that are valid integers are automatically cast as integers in PHP.

From the manual:

The key can either be an integer or a string. The value can be of any type. ... Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.

reformed
  • 4,505
  • 11
  • 62
  • 88
  • var_dump(array_key_exists(12, $array)); also returns false. and when making $array['12'] = 'X'; I will have two '12' keys in array. – gnysek Aug 24 '16 at 13:15
  • The manual isn't wrong. Take this as an object lesson of not casting objects and expecting the result to behave like an ordinary array. If you want an array, use the appropriate parameter in `json_decode()`. – reformed Aug 24 '16 at 14:06