array_unique removes values ββfrom the array that are duplicates, but the keys of the array are preserved.
So an array like this:
array(1,2,2,3)
will be filtered as
array(1,2,3)
but the value "3" will store its key "3", so the resulting array is really
array(0 => 1, 1 => 2, 3 => 3)
And json_encode cannot encode these values ββinto a JSON array, because keys do not start from scratch without holes. The only general way to recover this array is to use a JSON object for it.
If you want to always generate a JSON array, you must renumber the keys of the array. One way is to combine the array with an empty one:
$nonunique = array(1,2,2,3); $unique = array_unique($nonunique); $renumbered = array_merge($unique, array()); json_encode($renumbered);
Another way to achieve this would be to allow array_values ββto create a new sequentially indexed array for you:
$nonunique = array(1,2,2,3); $renumbered = array_values(array_unique($nonunique)); json_encode($renumbered);
Sven
source share