Using PHP’s array_unique() Function to Remove Duplicate Array Elements
This article explains PHP’s array_unique() function, detailing its syntax, parameters, return value, and optional sorting flag, and provides code examples that demonstrate how to remove duplicate elements from arrays and control sorting behavior.
In PHP programming, array manipulation is common. The built‑in array_unique() function removes duplicate values from an array and returns a new array.
Syntax of array_unique()
<code>array_unique(array $array, int $sort_flag = SORT_STRING): array</code>Parameter explanation
$array : the input array to be deduplicated.
$sort_flag : optional flag that determines how the array elements are sorted during deduplication.
Return value: an array containing only the first occurrence of each value.
Usage of array_unique()
<code><?php
// Define an array with duplicate elements
$fruits = array("apple", "banana", "orange", "apple", "melon", "banana");
// Remove duplicates
$uniqueFruits = array_unique($fruits);
// Output the result
print_r($uniqueFruits);
?>
</code>The code defines $fruits , calls array_unique() to produce $uniqueFruits , and prints the deduplicated array.
Running the script yields:
<code>Array
(
[0] => apple
[1] => banana
[2] => orange
[4] => melon
)
</code>As shown, the duplicate entries “apple” and “banana” appear only once, while the other elements remain unchanged.
The optional $sort_flag argument can be set to control the sorting behavior. Two common values are:
SORT_STRING (default): treats elements as strings and sorts them lexicographically.
SORT_REGULAR : compares elements using regular PHP comparison rules.
Example with $sort_flag
<code><?php
$numbers = array(1, 3, 5, 2, 5, 4);
// Remove duplicates and sort as strings
$uniqueNumbers = array_unique($numbers, SORT_STRING);
// Output the result
print_r($uniqueNumbers);
?>
</code>The output is:
<code>Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 4
[5] => 5
)
</code>By specifying $sort_flag = SORT_STRING , the numeric values are treated as strings, sorted in dictionary order, and the resulting array is ordered ascending.
The array_unique() function is a convenient tool in PHP for quickly removing duplicate elements from arrays. Using the optional $sort_flag parameter, developers can also control the sorting method, simplifying array handling and improving code efficiency.
PHP learning recommendations
Vue3+Laravel8+Uniapp Beginner to Real‑World Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Advanced Recommended Course
Workerman+TP6 Real‑time Chat System – Limited Time Offer
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.