unset() converts array into object

I am not so sure why it converts to an object instead of an array. That's surely because there no index 0 (indeed).

To prevent that, use array_values that reconstructs the indexes of the array:

unset($myArray[0]);
$myArray = array_values($myArray);

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 don't want to mutate the original array, or potentially have several gaps, then array_values is the way to go, which returns a new array without gaps:

array_values($myArray);

Tags:

Php

Arrays

Json