Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unset() converts array into object

Tags:

json

arrays

php

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.

like image 993
Dan Sebastian Avatar asked Feb 27 '16 16:02

Dan Sebastian


1 Answers

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);
like image 167
trincot Avatar answered Sep 29 '22 13:09

trincot