If I delete an element from an array with integer indices, and then apply the json_encode function to it, I get a string with a JavaScript object instead of a string with an array.

Here is a sample code:

 $a = [1, 2, 3]; unset($a[0]); echo(json_encode($a)); // {"1":2,"2":3} 

How to get the output string with an array?

In the case of the example above, the output should be like this:

 [2,3] 
  • Strictly speaking, json_encode returns a string. - vp_arth
  • @vp_arth, of course, we are talking about lines - Dmitriy Simushev
  • Although you are right, the heading should not be changed, so relevant) - vp_arth

2 answers 2

Why is this happening:

When deleting an item (which is not the last one), a “hole” appears in the array keys. At the same time, the json_encode function processes such an array not as an array with integer keys, but as an associative array (to which a JavaScript object is mapped).

What to do:

In order to get an array output, you need to normalize its keys, for example, using the array_values function:

 $a = [1, 2, 3]; unset($a[0]); $a = array_values($a); echo(json_encode($a)); // [2,3] 

    Dima, everything is available explained, from myself just add another 1 option to remove the element from the array function array_splice .

    Removes part of an array and replaces it with something else.

     $a = [1, 2, 3]; array_splice($a , 0, 1); echo(json_encode($a));