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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement