I have an array from which I want to unset the first item, but when I do so, and I send the info as JSON, the result is read as an object.
The PHP array looks like this:
$myArray = ["one", "two", "three", "four"]
and when I send this as JSON with json_encode($myArray)
it is as I expect:
["one","two","three","four"]
But then when I first unset:
unset($myArray[0]);
...the JSON I get from json_encode($myArray)
reads:
{"1":"one","2":"two"}
What makes it so, and how do I prevent it from showing up in object-notation?
From what I'm seeing, in PHP, the remaining array behaves like an array, and I can use array functions, such as array_search
, array_intersect
, etc.
In JSON, arrays always start at index 0. So if in PHP you remove element 0, the array starts at 1. But this cannot be represented in array notation in JSON. So it is represented as an object, which supports key/value pairs.
To make JSON represent the data as an array, you must ensure that the array starts at index 0 and has no gaps.
To make that happen, don't use unset, but instead use array_splice:
array_splice(myArray, 0, 1);
That way your array will shift, ensuring the first element will be at index 0.
If it is always the first element you want to remove, then you can use the shorter array_shift:
array_shift(myArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With