PHP array to JSON: objects vs lists, numeric keys and encoding errors
Why json_encode() sometimes gives you an object instead of a list, how to keep floats and slashes intact, and how to catch the silent false that malformed UTF-8 returns.
On this page
json_encode($array) is a one-liner, but it hides a few rules that cause most “the API returns the wrong shape” bugs. Here they are, with the flags that fix them. To convert in the other direction, or to turn a JSON sample into a PHP array literal, use the JSON ↔ PHP array converter.
List or object? It depends on the keys
PHP has one array type; JSON has two. json_encode() produces a JSON list only when the keys are exactly 0, 1, 2, … in order. Anything else becomes an object.
json_encode(['a', 'b']); // ["a","b"]
json_encode([1 => 'a', 2 => 'b']); // {"1":"a","2":"b"}
json_encode(['a', 'b', 'c'] ); // ["a","b","c"]
$items = array_filter(['a', '', 'c']); // keys 0 and 2
json_encode($items); // {"0":"a","2":"c"} (surprise)
json_encode(array_values($items)); // ["a","c"]
array_filter(), unset() and array_unique() keep the original keys, so wrap the result in array_values() before encoding a list. PHP 8.1 added array_is_list() if you want to assert it.
Empty arrays and forced objects
An empty PHP array always encodes as []. If the consumer expects {}, cast it or use the flag:
json_encode(['settings' => (object) []]); // {"settings":{}}
json_encode([], JSON_FORCE_OBJECT); // {}
JSON_FORCE_OBJECT applies to every nested array, which is rarely what you want. The (object) cast is more precise.
Keep floats, slashes and Unicode readable
$flags = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION;
echo json_encode(['price' => 10.0, 'url' => 'https://example.com/a', 'name' => 'Zoë'], $flags);
// {"price":10.0,"url":"https://example.com/a","name":"Zoë"}
Without JSON_PRESERVE_ZERO_FRACTION, 10.0 becomes 10, which strict consumers read as an integer. Add JSON_PRETTY_PRINT for humans. Float precision follows the serialize_precision ini setting; leave it at the default -1 for the shortest exact representation.
Catch encoding errors
By default json_encode() returns false on failure, and echo false prints nothing. The usual cause is a string that is not valid UTF-8, often from a legacy latin1 database column.
try {
$json = json_encode($data, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
// "Malformed UTF-8 characters, possibly incorrectly encoded"
}
Fix the data at the source (set the connection charset to utf8mb4). As a last resort, JSON_INVALID_UTF8_SUBSTITUTE replaces bad bytes with U+FFFD instead of failing.
Objects: control the output with JsonSerializable
Public properties are encoded; private and protected ones are not. To choose the shape, implement JsonSerializable:
final class Money implements JsonSerializable
{
public function __construct(private int $cents, private string $currency) {}
public function jsonSerialize(): array
{
return ['amount' => $this->cents / 100, 'currency' => $this->currency];
}
}
Decoding: arrays or objects
json_decode($json) gives stdClass objects; json_decode($json, true) gives associative arrays. Always pass JSON_THROW_ON_ERROR, and remember that very large integers lose precision unless you add JSON_BIGINT_AS_STRING. To check a payload is valid JSON without decoding it, PHP 8.3 added json_validate().