Paul Francis Paul Francis - 6 months ago 25
JSON Question

Removing array values without losing quotes

My Array :

$val=array('a','b','c');
echo json_encode($val);


Output :
["a","b","c"]


Using unset to remove 'b' from location '1' :
unset($val[1]);


Output:
{"0":"a","2":"c"}


Expecting Output as :
["a","c"]


Is there any solution ? to get rid of keys and curl brackets and get output as expected!

Answer

You need to reset array keys. Check this:

<?php

$val=array('a','b','c');
echo json_encode($val);

unset($val[1]);

echo json_encode($val); //outputs {"0":"a","2":"c"}


$val = array_values($val); //reset array keys
echo json_encode($val); //outputs ["a","c"]
Comments