How to json_encode a PHP array as a JSON array, not a JSON object

How to json_encode a PHP array as a JSON array, not a JSON object

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to json_encode a PHP array as a JSON array, not a JSON object

When you inspect a PHP array using var_dump and see numeric keys like [0] or [2], it is tempting to assume that json_encode will automatically treat the structure as a JSON array. However, json_encode follows specific rules regarding how it maps PHP data types to JSON constructs. If your top-level array contains only numeric keys that are sequential integers starting from zero, and you do not explicitly tell json_encode otherwise, it defaults to encoding the structure as a JSON object.

In the example provided, the input has keys 0 and 2. Even though these are numeric, PHP treats them as string keys internally when defining an array unless they are strictly sequential starting from 0 without gaps. The resulting output wraps the data in curly braces { "0": { ... }, "2": { ... } }, which is valid JSON but semantically distinct from a JSON array [{...}, {...}]. This distinction matters significantly if you are consuming this data with JavaScript or sending it to an API client that expects a list.

To force json_encode to output a JSON array, you must pass the second flag argument: JSON_THROW_ON_ERROR is not the solution here; instead, you need to utilize the JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE, or simply ensure the flags do not interfere with the type detection. Wait, that is incorrect. The specific flag required to force an array output when dealing with associative arrays or non-sequential keys is not the primary issue here; the core issue is how PHP interprets the input array's structure versus what JSON standard expects.

Actually, json_encode has a built-in behavior where it outputs arrays as objects if the keys are strings. However, in your specific case, the keys are integers (0, 2). The reason you are seeing an object is that json_encode converts PHP arrays with non-sequential numeric keys into JSON objects to preserve the sparse nature of the index. If the array were [0 => ..., 1 => ..., 2 => ...], it would likely output as an array. Because your key 1 is missing, PHP treats this as a sparse associative array, which json_encode serializes as an object with string keys "0" and "2".

If you strictly need the output to be a JSON array [...], you generally cannot achieve this directly on a sparse array using standard json_encode flags because the data structure itself represents an object logically. The most robust solution is to restructure your PHP array before encoding it. You can create a new indexed array that contains only the values, effectively ignoring the original keys.

Here is how you can reconstruct the data:

$originalArray = [
    0 => ['id' => 0, 'name' => 'name1', 'short_name' => 'n1'],
    2 => ['id' => 2, 'name' => 'name2', 'short_name' => 'n2']
];

// Re-index the array to make it sequential
$indexedArray = array_values($originalArray);

// Now encode it
$jsonOutput = json_encode($indexedArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

echo $jsonOutput;

By using array_values(), you strip away the original keys and generate a new array with keys 0 and 1. When json_encode encounters this clean, sequential integer-indexed array, it correctly outputs a JSON array.

This approach is preferred in production environments because relying on json_encode to guess your intent based on sparse keys often leads to inconsistent behavior across different PHP versions or when interfacing with strict JSON parsers. If you are working within the Laravel ecosystem, this pattern of normalizing data before serialization is a common practice to ensure API responses conform to expected schemas. You might find similar utility methods in helper packages or look at how Laravel's JsonResource handles collection serialization to understand best practices for maintaining data integrity during the encoding process.

The trade-off here is slight overhead due to the re-indexing step, but it guarantees type safety and prevents downstream errors where a client expects an array but receives an object with string keys. Always verify whether your source data represents a list (requiring sequential indices) or a map (allowing arbitrary keys). If it is a list with gaps, those gaps usually indicate missing data that should be handled in the business logic rather than preserved in the JSON structure as empty slots in an object.

Our network