I noticed something interesting today using unset() and json_decode/json_encode. Here is the code:
echo "<h3>1) array as string</h3>";
$sa = '["item1","item2","item3"]';
var_dump($sa);
echo "<h3>2) array as string decoded</h3>";
$sad = json_decode($sa);
var_dump($sad);
echo "<h3>3) array as string decoded, then encoded again. <small>(Note it's the same as the original string)</small></h3>";
$sade = json_encode($sad);
var_dump($sade);
echo "<h3>4) Unset decoded</h3>";
unset($sad[0]);
var_dump($sad);
echo "<h3>5) Encode unset array. <small>(Expecting it to look like original string minus the unset value)</small></h3>";
$ns = json_encode($sad);
var_dump($ns);
echo "<h3>6) Decode Encoded unset array</h3>";
var_dump(json_decode($ns));
and the result:
So my question is: Why does unset() change the way json_encode makes it a string? And how can I achieve the same string format as the original?
json doesn't need to include the keys for a contiguous key sequence from offset zero.
Unsetting a value from a standard enumerated array leaves a gap in the sequence of keys for that array, it doesn't adjust the remaining keys in any way; so the json needs to reflect this difference by including the keys
If you want to reset the keys to a contiguous sequence from offset 0 again, then
unset($sad[0]);
$sad = array_values($sad);
and then json encode/decode again
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With