2

Why is it that

echo json_encode(array_unique([1,2,3,4,4]));

Outputs

[1,2,3,4]

And

echo json_encode(array_unique([1,2,3,3,4]));

Outputs

{"0":1,"1":2,"2":3,"4":4}

This has lead to some very odd bugs for me, and I simply cannot understand what's going on here. I just want to remove the duplicates from the array and have it returned as an array.

6
  • array_unique() does not reindex your array, so when you encode it in json it will include the keys in the output. Commented Jan 2, 2017 at 0:42
  • stackoverflow.com/questions/30362192/… Commented Jan 2, 2017 at 0:42
  • @Rizier123 - but why not in the first case? Both arrays supplied as arguments have duplicate integers in them. Commented Jan 2, 2017 at 0:43
  • @nickdnk Read: stackoverflow.com/a/11722121/3933332 there are many similar questions. Commented Jan 2, 2017 at 0:43
  • @nickdnk what you need is this: json_encode(array_values(array_unique([1,2,3,3,4]))); Commented Jan 2, 2017 at 0:44

1 Answer 1

3

array_unique([1,2,3,4,4]) returns:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

Note that the keys are sequential

While array_unique([1,2,3,3,4])) returns:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [4]=>
  int(4)
}

Note the jump between the key 2 and the key 4.

Because of that - json_encode will omit the keys in the first array (and keep it as array object), while in the second array - the json_encode will look at your array as object and will keep the keys.

You can use array_values (to get the values and ignore the keys).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.