In PHP, you can convert an array into a collection of unique elements using the array_unique() function, which will remove duplicate elements and return a new array containing unique elements. The array_unique() function accepts an array as a parameter and can optionally specify the sorting method, such as ascending or numerical sorting. The sorting and deduplication order can be customized using the SORT_FLAG parameter.
Convert an array to a collection of unique elements with PHP
Converting an array to a collection of unique elements is very simple in PHP. This article will show you how to do this using the built-in function array_unique()
.
array_unique() Function
array_unique()
The function can remove duplicate elements from an array and return a new array containing unique elements. It accepts the following parameters:
array
: The array to remove duplicates. sort_flags
: Optional parameter used to specify how to sort the array. sort_flags
The parameter can specify the following values:
SORT_REGULAR
: Default value, sort by standard comparison operators. SORT_NUMERIC
: Sort by numeric value. SORT_STRING
: Sort by string value. SORT_LOCALE_STRING
: Sort by localized string value. SORT_ASC
: Sort in ascending order. SORT_DESC
: Sort in descending order. Practical case
The following is a practical case for removing duplicate elements from an array:
<?php $array = [1, 2, 3, 4, 5, 1, 2, 3]; $uniqueArray = array_unique($array); print_r($uniqueArray); ?>
Output result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
As you can see, the duplicate elements have been removed from the array.
If you want to sort the array and then remove duplicate elements, you can use the array_unique()
function with the SORT_FLAG
parameter:
<?php $array = [5, 3, 1, 3, 2, 4, 2, 1]; $uniqueSortedArray = array_unique($array, SORT_NUMERIC | SORT_ASC); print_r($uniqueSortedArray); ?>
Output result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
In the above example, we sort the array in ascending order and then remove duplicate elements.
The above is the detailed content of Convert PHP array to collection of unique elements. For more information, please follow other related articles on the PHP Chinese website!