Skip to content
Advertisement

Remove an element from Json array

I stored my array content in form of json array to database .

Format: [“1″,”2″,”3”]

Now i retrieved the value from database and tried to remove the third element “2” from same structure.

My code for that is

$numbers= json_decode($numbers_db,true); //json decode numbers array got from DB
if (($key = array_search(2, $numbers)) !== false) {
                    unset($numbers[$key]);
                 }
                 $numbers_final = json_encode($numbers);

Now i expected $numbers_final to be of the format: ["1","3"]

But it resulted to {"0":"1","2":"3"}

Advertisement

Answer

The problem is that when you unset() an element, the indexes are kept intact. In this case, the index 1 doesn’t exists anymore so the array is converted into an object.

To force the array to be re-indexed sequentially yo can do something like this:

$numbers_db  = '["1", "2", "3"]';

echo $numbers_db;

$numbers= json_decode($numbers_db,true); //json decode numbers ar

if (($key = array_search(2, $numbers)) !== false) {
    unset($numbers[$key]);
    $numbers = array_values($numbers);
}
$numbers_final = json_encode($numbers);

echo $numbers_final;                 
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement