Remove item from Json array

I saved the contents of the array as a json array in the database.

Format: ["1", "2", "3"]

Now I got the value from the database and tried to remove the third element "2" from the same structure.

My code for this

$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 have the format: ["1","3"]

But this led to {"0":"1","2":"3"}

0
source share
1 answer

The problem is that when you unset() an element, the indexes are kept intact. In this case, index 1 no longer exists, so the array is converted to an object.

To make the array re-indexed sequentially, you 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; 
+2
source

Source: https://habr.com/ru/post/951653/


All Articles