Duplicate Keys In JSON

<?php

// JSON is decoded
print_r(json_decode('{"a":1,"b":3,"a":2}'));

// with an error
print json_last_error_msg();

// it is actually an error
print_r(json_decode('{"a":1,"b":3,a":2}', flags: JSON_THROW_ON_ERROR));

?>

JSON tolerates duplicate keys in an object, although it is not recommended.

json_decode() decodes it, and keeps the last key available in the object in the result. With default configuration, this works without feedback.

One need to call json_last_error_msg() to actually get the feedback.

Using ‘flags’ option to throw error is stricter, and treats the warning as an error.

See Also

PHP Features

Last updated: 06 August 2026