Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unset() change the way json_encode formats the string?

Tags:

json

php

unset

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:enter image description here

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?

like image 436
Jason Spick Avatar asked Jan 08 '23 05:01

Jason Spick


1 Answers

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

like image 112
Mark Baker Avatar answered Jan 13 '23 13:01

Mark Baker