Code Logo

Remove Duplicates with array_unique()

Published at25 Jul 2026
PHP Collections Easy 0 views
Like0

Write a PHP function that takes an array and returns a new array with duplicate values removed using array_unique(). Only the first occurrence of each value is kept.

array_unique() is a PHP function that takes an array and returns a new array with duplicate values removed. It compares values as strings by default (using (string) casting), but can use a comparison flag like SORT_NUMERIC or SORT_REGULAR.

The function preserves the original keys of the first occurrence of each value. Use array_values() after array_unique() if you need re-indexed numeric keys.

Time complexity is O(n log n) as it sorts the array internally to find duplicates. For large arrays, consider using array_count_values() for frequency-based operations.

Example Input & Output

Example 1
Input
[]
Output
[]
Explanation

Empty array

Example 2
Input
(['a','b','a'])
Output
['a','b']
Explanation

String duplicates

Example 3
Input
[1,2,2,3,3,3]
Output
[1,2,3]
Explanation

Remove duplicates

Example 4
Input
[1,2,3]
Output
[1,2,3]
Explanation

Already unique

Example 5
Input
[5,5,5]
Output
[5]
Explanation

All same

Algorithm Flow

Recommendation Algorithm Flow for Remove Duplicates with array_unique()
Recommendation Algorithm Flow for Remove Duplicates with array_unique()

Solution Approach

function solution($arr) {
    return array_values(array_unique($arr));
}

Best Answers

php - Approach 1
<?php
function solution($arr) {
    return array_values(array_unique($arr));
}