Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, 3

Why 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

Thanks for reading!

Donate to the site — we work hard for you.