Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

baskarks's avatar

how to encode json key as integer instead of string

while encode numeric array it should show the key as integer instead of string

0 likes
2 replies
martinbean's avatar

@baskarks JSON only has numeric arrays, or objects. If the keys are numbers, then JSON will interpret it as a numeric array and reset the keys.

alden8's avatar

In JSON, keys in objects are always of type string. This is a requirement of the JSON specification and not something that can be changed. When you encode an associative array in PHP with json_encode, the keys are always output as strings in the resulting JSON object.

If you have a numerically indexed array, and you want the indices to appear as numbers in the JSON output, you can use a plain (non-associative) array. In this case, json_encode will output a JSON array, not a JSON object, and the indices will not be included in the output.

Here's an example:

$array = array(1 => 'foo', 2 => 'bar', 3 => 'baz'); echo json_encode($array);

This will output: {"1":"foo","2":"bar","3":"baz"}

But if you use a non-associative array: $array = array('foo', 'bar', 'baz'); echo json_encode($array);

This will output: ["foo","bar","baz"]

In the second example, the indices (0, 1, 2) are not included in the output. They are implied by the order of the elements in the array.

Please or to participate in this conversation.