1

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

2 Answers 2

4

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;                 
Sign up to request clarification or add additional context in comments.

Comments

1

Use array_splice instead

array_splice($array,$offset,$length)

this will remove from the $offset element $length elements and re-index

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.