Master PHP’s array_unique(): Remove Duplicates and Sort Arrays Efficiently
Learn how to use PHP’s array_unique() function to eliminate duplicate values from arrays, understand its parameters—including optional sort flags—and see practical code examples that demonstrate deduplication and sorting for both string and numeric arrays.
In PHP programming, the
array_unique()function removes duplicate elements from an array and returns a new array.
The syntax is:
<code>array_unique(array $array, int $sort_flag = SORT_STRING): array</code>Parameter explanation:
$array: the array to be deduplicated.
$sort_flag: optional, determines how array elements are sorted.
Return value: the deduplicated array with only one instance of each duplicate.
Example of basic usage:
<code><?php
// Define an array with duplicate elements
$fruits = array("apple", "banana", "orange", "apple", "melon", "banana");
// Remove duplicates
$uniqueFruits = array_unique($fruits);
// Print the result
print_r($uniqueFruits);
?>
</code>The output is:
<code>Array
(
[0] => apple
[1] => banana
[2] => orange
[4] => melon
)
</code>When using
array_unique(), an optional
$sort_flagcan be set to control sorting. Two possible values are:
SORT_STRING (default): treats elements as strings and sorts them lexicographically.
SORT_REGULAR: compares elements using regular comparison.
Example with
SORT_STRING:
<code><?php
$numbers = array(1, 3, 5, 2, 5, 4);
// Remove duplicates and sort as strings
$uniqueNumbers = array_unique($numbers, SORT_STRING);
// Print the result
print_r($uniqueNumbers);
?>
</code>The output is:
<code>Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 4
[5] => 5
)
</code>Summary
The
array_unique()function efficiently removes duplicate elements from arrays in PHP. By specifying the optional
$sort_flag, you can also control the sorting method during deduplication, simplifying array handling and improving code efficiency.
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.