0

I get a strange behavior when I remove data from my array with unset

$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);

And I append more objects to the array

$array[] = $value1;
$array[] = $value2;
echo json_encode($array);

When I convert $array into an object I get this key values insted of index values

{"2":{"name":"mario"},"3":{"name":"hector"}}

Expected output

[{"name":"mario"},{"name":"hector"}]
MAximy
  • 33
  • 3
  • Does this answer your question? [Deleting an element from an array in PHP](https://stackoverflow.com/questions/369602/deleting-an-element-from-an-array-in-php) – Xupitan Jun 16 '22 at 02:07

1 Answers1

1

That's because php unset doesn't reduce the length of the array, it just empty the given key.

Since it doesn't change the length, whe. You do $array[] = something you continue incrementing the index, creating the 2 and 3 index you are seeing.

When you do json_encode, since the keys doesn't start from zero (or aren't contiguous), it need to represent this array as an object.

Exemplifying:

$var1 = [1 => 'a', 3 => 'b'];

Can only be serialized to

{"1": "a", "3": "b"}

Because you can't define the index of an array item using JSON.

Solution

You can still use unset(), but you need to get only array values using the array_values() function:

$array = [['name' => "pepe"], ['name' => 'marta']];
unset($array[0]);
unset($array[1]);

$array[] = $value1;
$array[] = $value2;
// $array is now [2=>$value1, 3=>$value2]

$array = array_values($array);
// $array is now [$value1, $value2]

echo json_encode($array);
// Now the json outputs as expected by you: ["value1", "value2"]
Elias Soares
  • 9,884
  • 4
  • 29
  • 59