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"]