Why json_encode() Turns Numeric Arrays into Objects and How to Fix It
When you call json_encode() on a PHP array containing numeric keys, you might expect a standard JSON array like [["Afghanistan", 32, 12], ["Albania", 32, 12]]. Instead, the output often looks like { "2": [["Afghanistan", 32, 12]], "4": [...] }, where the numeric keys have been converted into string keys inside a JSON object. This behavior isn't arbitrary; it is a deliberate feature of the PHP engine and the JSON specification that many developers find surprising when they don't explicitly control their data structures.
The root cause lies in how PHP distinguishes between arrays and objects during serialization. When json_encode() processes a native PHP array, it checks the keys. If all keys are integers starting from zero with no gaps (e.g., 0, 1, 2), PHP treats the structure as a list and outputs JSON syntax using square brackets [...]. However, if the keys are stringsâeven if they look like numbersâor if the sequence is broken (e.g., 0, 1, 3 instead of 0, 1, 2), json_encode() assumes the data represents a map or dictionary. In this case, it generates valid JSON object syntax with curly braces {...} and keys as strings.
In the specific scenario provided by the source material, the user receives output like { "2": [...] }. This implies that the PHP array being passed to json_encode() likely has string keys (e.g., ['2' => [...]]) or is missing the initial index 0. The function strictly adheres to the JSON RFC, which states that object keys must be strings. Since raw numbers in JSON objects require quotes, the result is a JSON object rather than an array.
To achieve the desired format of [[...], [...]] without resorting to regex replacements or manual string parsing, you must ensure the PHP data structure itself represents a list before encoding. The most reliable approach is to iterate over the data using array_values() or reconstruct the indices if gaps exist. If your input array looks like this:
$data = [
'2' => ['Afghanistan', 32, 12],
'4' => ['Albania', 32, 12]
];
The resulting JSON will always be an object because the keys are strings. To fix this, you need to re-index the array:
$data = array_values($data);
$json = json_encode($data);
// Result: [["Afghanistan",32,12],[...]]
array_values() discards the original keys and creates a new zero-based integer sequence. This forces json_encode() to recognize the structure as an array. This is the canonical solution because it operates at the data model level rather than manipulating the serialized string.
There are trade-offs to consider when choosing this approach. If your application relies on maintaining specific key associations (like caching strategies that read from the original keys), re-indexing might break those assumptions. In such cases, you must ensure the original key is preserved in the value or stored separately. Additionally, if the array is massive and performance is critical, array_values() creates a new copy of the data. For smaller datasets, this overhead is negligible compared to the clarity it provides.
Another consideration involves mixed types. If an array contains both numeric keys and associative keys (e.g., [0 => 'list', 'name' => 'Alice']), PHP treats the whole thing as an object in JSON output. To force array syntax, every key must be a contiguous integer starting at zero. If you encounter gaps in your indices, array_values() will fill them sequentially, which might alter the logical order if that order depended on the specific gap values.
For developers working within the Laravel ecosystem, similar principles apply when returning JSON responses or building API payloads. Ensuring data models return collections rather than loose arrays with string keys prevents unintended object serialization. While there are no built-in Laravel helpers that bypass this behavior without checking the underlying array structure, understanding PHP's core json_encode logic ensures predictable output regardless of the framework version.
Ultimately, the "trick" isn't about manipulating the JSON string after creation; it is about ensuring the input data matches the semantic meaning of a JSON array. By using array_values() or verifying that your keys are contiguous integers, you can reliably produce the expected array syntax without complex post-processing.