How to treat a php array as a regular list so when I add elements by numeric indices it keeps the keys in order [duplicate]

21 hours ago 2
ARTICLE AD BOX

To move PHP variables to JS on the client side, I use and like json_encode.

Unfortunately, PHP arrays are different from JS arrays, and often they are are encoded as objects, even if the keys are numeric.

This works fine:

<?php $arr = []; $arr[0]= 'A'; $arr[1]= 'BC'; $arr[2]= 'DEF'; echo json_encode($arr); // output: ["A","BC","DEF"] ?>

But, if I do not add the elements in pure ascending order, the array is encoded as an object:

<?php $arr = []; $arr[2]= 'DEF'; $arr[1]= 'BC'; $arr[0]= 'A'; echo json_encode($arr); // output: {"2":"DEF","1":"BC","0":"A"} ?>

Unfortunately, data arrives in reverse order. (Or I want it in reverse, finally.)

A suggested solution json_encode(array_values($arr)); does not apply, as it returns ["DEF","BC","A"]

What are my options?

copy one array into another one in reverse order? create an indexed array beforehand, and replace the values? do it on the JS side later? other ideas?
Read Entire Article