JSON_FORCE_OBJECT

When working with json_encode() and arrays, an array with ordered indexes will be an array by default.

$json = json_encode([0 => 'foo', 2 => 'bar']);
var_dump($json);
// string(21) "{"0":"foo","2":"bar"}"

// An array with ordered indexes will be array by default
$json = json_encode([0 => 'foo', 1 => 'bar']);
var_dump($json);
// string(13) "["foo","bar"]"

// JSON_FORCE_OBJECT will make it an object
$json = json_encode([0 => 'foo', 1 => 'bar'], JSON_FORCE_OBJECT);
var_dump($json);
// string(21) "{"0":"foo","1":"bar"}"


Found a typo? Something wrong with this content?

Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all contributors.