php-src
php-src copied to clipboard
json_decode() native arguments like JSON_OBJECT_AS_ARRAY have the wrong type when using strict type
Description
The following code:
<?php
declare(strict_types=1);
$test = '[{"foo":"bar"},{"foo":"baz"},{"foo":"bal"}]';
$data = json_decode($test, JSON_OBJECT_AS_ARRAY);
var_dump($data);
Resulted in this output:
PHP Fatal error: Uncaught TypeError: json_decode(): Argument #2 ($associative) must be of type ?bool, int given in /home/mdibbets/git/dugros-integrations/var/data/test/strict.php:4
Stack trace:
#0 /home/mdibbets/git/dugros-integrations/var/data/test/strict.php(4): json_decode()
#1 {main}
thrown in /home/mdibbets/git/dugros-integrations/var/data/test/strict.php on line 4
But I expected this output instead:
array(3) {
[0]=>
array(1) {
["foo"]=>
string(3) "bar"
}
[1]=>
array(1) {
["foo"]=>
string(3) "baz"
}
[2]=>
array(1) {
["foo"]=>
string(3) "bal"
}
}
PHP Version
8.0
Operating System
Ubuntu 20.04
That's because you're passing the flag to the wrong parameter.
json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed
https://www.php.net/manual/en/function.json-decode.php
Use either of these options.
// Named arguments, since PHP 8.0
$data = json_decode($test, flags: JSON_OBJECT_AS_ARRAY);
// Pass all parameters
$data = json_decode($test, null, 512, JSON_OBJECT_AS_ARRAY);
https://3v4l.org/noqH9