Unset () converts an array to an object

I have an array from which I want to remove the first element, but when I do this and send the information as JSON, the result is read as an object.

The PHP array is as follows:

$myArray = ["one", "two", "three", "four"] 

and when I send this as JSON with json_encode($myArray) , this happens as I expected:

 ["one","two","three","four"] 

But then, when I first disconnected:

 unset($myArray[0]); 

... the JSON I got from json_encode($myArray) reads:

 {"1":"one","2":"two"} 

What makes it so, and how can I prevent it from appearing in object notation?

From what I see, in PHP the remaining array behaves like an array, and I can use array functions like array_search , array_intersect , etc.

+8
source share
2 answers

In JSON, arrays always start at index 0. Therefore, if in PHP you delete element 0, the array starts at 1. But this cannot be represented in array notation in JSON. Thus, it is presented as an object that supports key / value pairs.

In order for JSON to represent data as an array, you must make sure that the array starts at index 0 and has no spaces.

For this to happen, do not use unset, but use array_splice instead :

 array_splice(myArray, 0, 1); 

This way your array will shift, ensuring that the first element has index 0.

If this is always the first element you want to remove, you can use a shorter array_shift :

 array_shift(myArray); 
+9
source

I'm not sure why it converts to object instead of array . This, of course, is because there is no index 0 (really).

To prevent this, use array_values , which restores the indexes of the array:

 unset($myArray[0]); $myArray = array_values($myArray); 
+8
source

Source: https://habr.com/ru/post/1244014/


All Articles