PHP: strange array behavior after object type goes into array

When you arraycast json_decoded (c $assoc = false), PHP creates an array with string indices:

$a = (array)json_decode('{"7":"value1","8":"value2","9":"value3","13":"value4"}');

var_export($a);

//array (
//  '7' => 'value1',
//  '8' => 'value2',
//  '9' => 'value3',
//  '13' => 'value4',
//)

And for some reason, these indexes are not available:

var_dump(isset($a[7]), isset($a['7']));

//false
//false

When you try to create the same array by PHP itself, it is created with numeric indices (the string is automatically converted), and the values ​​are available using both strings and numbers:

$c = array('7' => 'value1', '8' => 'value2', '9' => 'value3','10' => 'value4');

var_export($c);

var_dump(isset($c[7]), isset($c['7']));

//array (
//  7 => 'value1',
//  8 => 'value2',
//  9 => 'value3',
//  13 => 'value4',
//)
//
//true
//true

Does anyone know what is going on here? Is this some bug in older PHP versions (the problem seems to be fixed in PHP version> = 7.2, but I can't find anything related in changelog )?

Here is a demonstration of what is happening: https://3v4l.org/da9CJ .

+4
2

# 61655 ​​ 7.2.0:

, (, "22200" ) , .      HashTable , .

: $a["2000"] $a[2000], (array) . , , " " .

+3

TRUE json_decode()

<?php
$a = json_decode('{"7":"value1","8":"value2","9":"value3","13":"value4"}',TRUE);

var_export($a);

var_dump(isset($a[7]), isset($a['7']));

https://3v4l.org/YuF9B

0

Source: https://habr.com/ru/post/1692523/


All Articles