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.