4

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?

0

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

4

In number 5, if you notice the keys start at 1. Typically arrays (in both php and js/json) start with zero. A non-zero indexed array (or an array with non contiguous numbers) in json is an object literal, not an array. If you want the same string format, I suggest you json_decode passing the second parameter to force it to an array. Then you can use array functions that re-index the array as numeric such as array_shift or array_pop. Or when json_encoding the array, re-index the array yourself with array_values.

1 Comment

Put a different way, JS does not have associative arrays so json_encode() converts it to an object to preserve your keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.