Search code examples
phpjsonunset

PHP unset returns my json array with int indexes


i have a problem with my json index remover , so far i tryed this

$cars = json_decode($json_user , true);
foreach ($cars as $key => $value) {
    if (in_array('BH', $value)) {
        unset($cars[$key]);
    }
}
echo $cars = json_encode($cars);

With the JSON content

[{"code":"AB"},{"code":"BC"},{"code":"CD"}]

When using the script above to remove the index containing BC it returns me this

{"0":{"code":"AB"},"2":{"code":"CD"}}

instead of this

[{"code":"AB"},{"code":"CD"}]

Solution

  • It works as expected. The PHP arrays are association maps. Removing a key doesn't affect the other keys of the array.

    Use array_values() to reindex $cars before encoding it as JSON.