Encoding JSON

Encoding to JSON and the Flags That Matter

json_encode($value, $flags = 0, $depth = 512) makes a JSON array only from a list, meaning keys 0, 1, 2 in order. Every other array becomes an object, and so does an object's public properties.

Default and readable output, and how array shape decides [] or {}PHP
<?php
$book = ['title' => 'Café <b>PHP</b>', 'price' => 39.0, 'url' => 'https://example.com/b/1'];
echo json_encode($book), "\n", json_encode($book, JSON_UNESCAPED_UNICODE
  | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_HEX_TAG), "\n";
$list = ['a', 'b', 'c'];
unset($list[0]);                                  // keys 1 and 2: no longer a list
echo json_encode($list), ' ', json_encode(array_values($list)), ' ',
  json_encode([], JSON_FORCE_OBJECT), ' ', json_encode(['007', '2.50'], JSON_NUMERIC_CHECK),
  "\n";
Output
{"title":"Caf\u00e9 <b>PHP<\/b>","price":39,"url":"https:\/\/example.com\/b\/1"}
{"title":"Café \u003Cb\u003EPHP\u003C/b\u003E","price":39.0,"url":"https://example.com/b/1"}
{"1":"b","2":"c"} ["b","c"] {} [7,2.5]

For APIs, combine JSON_THROW_ON_ERROR (JSON Errors and Exception Mode) with both UNESCAPED flags. Use JSON_HEX_* for JSON inside a <script> block, and escape HTML as in 4.6.11. After unset(), re-index the array with array_values(). Avoid JSON_NUMERIC_CHECK, which turned the SKU "007" into 7.