Using PHP’s array_unique() Function to Remove Duplicate Elements and Sort Arrays
This article explains how PHP's built‑in array_unique() function can be used to eliminate duplicate values from one‑dimensional arrays, optionally sort the results with different flags, and provides clear code examples illustrating both deduplication and sorting behaviors.
In PHP development, removing duplicate elements from an array is a common task, and the built‑in array_unique() function provides a straightforward solution.
The function signature is:
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )$array is the input array to be processed, and the optional $sort_flags parameter determines how the resulting array is sorted.
A basic example demonstrates deduplication:
<?php
// Define an array with duplicate values
$array = array(1, 2, 2, 3, 4, 4, 5);
// Remove duplicates
$result = array_unique($array);
// Output the result
print_r($result);
?>The output is:
Array
(
[0] => 1
[1] => 2
[3] => 3
[4] => 4
[6] => 5
)Note that array_unique() keeps the first occurrence of each value and discards later duplicates, so the original order of unique elements is preserved.
The function works only with one‑dimensional arrays; handling multidimensional arrays requires custom logic such as recursion.
Beyond deduplication, array_unique() can also sort the array when a $sort_flags value is supplied. The available flags are:
SORT_REGULAR – regular comparison
SORT_NUMERIC – numeric comparison
SORT_STRING – string comparison
For example, sorting numerically while removing duplicates:
<?php
// Define an array with duplicate values
$array = array(4, 1, 3, 2, 2, 1, 4);
// Remove duplicates and sort numerically
$result = array_unique($array, SORT_NUMERIC);
// Output the result
print_r($result);
?>The output shows the array sorted by numeric value:
Array
(
[0] => 4
[1] => 1
[2] => 3
[3] => 2
)In summary, array_unique() is a useful PHP function for quickly eliminating duplicate entries and, with optional flags, sorting the resulting array, making it a versatile tool for backend developers.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.