Understanding PHP json_encode Output: When Arrays Become Objects
This article explains why PHP's json_encode sometimes returns a JSON object instead of an array, demonstrates several common scenarios, and provides practical code solutions to ensure the desired array format in the resulting JSON.
When converting PHP arrays to JSON with json_encode, the resulting JSON may be an object rather than an array if the array indices are not a consecutive sequence starting from zero. This guide records typical problems encountered in daily development and offers concrete fixes.
Problem: Array to JSON sometimes yields an object, sometimes an array.
Case 1:
$arr = [1, 2, 3]; // zero‑based indices
echo json_encode($arr); // [1,2,3]
$arr = [1=>1, 2=>2, 3=>3]; // non‑zero‑based indices
echo json_encode($arr); // {"1":1,"2":2,"3":3}If an array output is required, re‑index the array:
$arr = [1=>1, 2=>2, 3=>3];
echo json_encode(array_values($arr)); // [1,2,3]Case 2:
$arr = [];
$arr[0] = 'xxx';
$arr[1] = 'yyy';
echo json_encode($arr); // ["xxx","yyy"]
$arr = [];
$arr[1] = 'yyy';
$arr[0] = 'xxx';
echo json_encode($arr); // {"1":"yyy","0":"xxx"}Because the insertion order changes, the JSON representation differs.
Friend's attempted fix:
$arr = [];
$arr[1] = 'yyy';
$arr[0] = 'xxx';
$arr = array_values($arr);
echo json_encode($arr); // ["yyy","xxx"]This produces the wrong order because array_values re‑indexes based on the original order.
Correct solution:
$arr = [];
$arr[1] = 'yyy';
$arr[0] = 'xxx';
ksort($arr);
echo json_encode($arr); // ["xxx","yyy"]Case 3:
$arr = [];
$arr[0] = 'yyy';
$arr[2] = 'xxx';
print_r($arr);
echo json_encode($arr);
/*
Array
(
[0] => yyy
[2] => xxx
)
{"0":"yyy","2":"xxx"}
*/Case 4:
$arr = [];
echo json_encode($arr); // []Summary:
When array indices are not a continuous sequence starting from 0, json_encode outputs a JSON object.
To obtain a JSON array, ensure indices are consecutive from 0 without gaps, or re‑index the array using array_values or sort the keys with ksort before encoding.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
