I am creating an array by doing $x = [];
If I do:
$x = [];
$x[2] = 'a';
$x[1] = 'b';
$x[0] = 'c';
echo json_encode($x);
I get: {"2":"a","1":"b","0":"c"}.
If I do:
$x = [];
array_push($x,'c');
array_push($x,'b');
array_push($x,'a');
echo json_encode($x);
I get: ["c","b","a"]
Can I build an array like in the array_push example by position $x[] instead of an associative array?
I want to do the $x[] syntax to update the array by position and get the ["c","b","a"] array. There must be some syntax or construction that I am not using correctly.
Thanks in advance for any help.
4
Answers
Based on the comments, this cannot be controlled like in javascript where you can create an array by doing [] and an object by doing {}.
My solution is this:
Adding in ksort(), before the JSON encoding, does the trick:
This sorts the array by the keys specified and returns:
See: https://3v4l.org/Bi28c
You can use
array_unshift($x, ...['a', 'b', 'c'])
(or by one element) instead ofarray_push
to always add element to the beginning of array instead of end.Example
Although users (and other languages – including JSON, which is not JavaScript) often distinguish between "associative arrays" and "ordered arrays", PHP does not.
Every array allows access to its items in two ways:
$foo[$bar]
, you are looking up or setting an item by its keyThe reason your current code doesn’t give the result you wanted is that from PHP’s point of view, there is no such thing as "the third position" in an empty array. The first item added to an empty array is always the first in the list, regardless of its key.
You can sort the items based on their keys with
ksort
; but this won’t create or delete any items, it will just change the order in the list.If you want to pre-fill an array with a set number of
null
items, you can usearray_fill
. For instance:You can also choose to add items "before" or "between" other elements, using
array_splice
with a length of 0:Positions past the current last position still just mean "add at end", though, they don’t create any "gaps":
The other thing you can do is re-number the keys of an array, using
array_values
. That allows you to close gaps, but not create them: