How to remove duplicates from an array
Short answer
array_unique() keeps the first occurrence of each value:
<?php
echo implode(', ', array_values(array_unique([1, 2, 2, 3, 1])));Output:
1, 2, 3Why array_values()
array_unique() preserves the original keys, which leaves gaps in the numbering. array_values() renumbers the elements:
<?php
print_r(array_unique(['a', 'b', 'a', 'c']));Output:
Array
(
[0] => a
[1] => b
[3] => c
)Functions used in this recipe
- array_unique — Removes duplicate values from an array.