This question already has an answer here:
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.
</div>
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 key4
.
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
).