23

I'm experiencing odd behavior with json_encode after removing a numeric array key with unset:

$a = array(
    new stdclass,
    new stdclass,
    new stdclass
);
$a[0]->abc = '123';
$a[1]->jkl = '234';
$a[2]->nmo = '567';

printf("%s\n", json_encode($a));
unset($a[1]);
printf("%s\n", json_encode($a));

Program Output

[{"abc":"123"},{"jkl":"234"},{"nmo":"567"}]
{"0":{"abc":"123"},"2":{"nmo":"567"}}

The first time $a is converted to JSON, it's encoded as an array. The second time, it's encoded as an object. Why is this happening, and how can I prevent it?

0

3 Answers 3

22

The reason for that is that your array has a hole in it: it has the indices 0 and 2, but misses 1. JSON can't encode arrays with holes because the array syntax has no support for indices.

You can encode array_values($a) instead, which will return a reindexed array.

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

4 Comments

Alternatively you can sort the array after unsetting an element.
@NullUserException Though that will have the side effect of, well, sorting your array.
For those wondering about the unset behavior, view the following link and scroll down to "Useful functions": us3.php.net/manual/en/language.types.array.php "The unset() function allows removing keys from an array. Be aware that the array will not be reindexed"
@NullUserException Great addition! Needed to sort the array anyway - killing two birds with one stone.
7

In addition to the array_values technique it is possible to use array_splice and remove an element and re-index in one step:

unset($a[1]);

Instead:

array_splice($a, 1, 1);

2 Comments

absolutely perfect way to do the job without messing up the collection, thanks!
This. The most elegant way.
2

Try to use JSON_FORCE_OBJECT option for json_encode, like: json_encode($a, JSON_FORCE_OBJECT) so you will always have the same result.

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.