What is the purpose of the php array_unique function?
array_unique is a function in PHP that removes duplicate elements from an array and returns a new array containing only unique elements from the original array.
Specifically, the array_unique function will go through the given array, keeping only one instance of duplicate elements and rearranging the unique elements in their original order to form a new array. Duplicate elements will only appear once in the new array.
Here is the syntax for the array_unique function:
array_unique(array $array, int $sort_flags = SORT_STRING): array
Explanation of parameters:
- $array: the array to be processed.
- $sort_flags (optional): Specifies the sorting criteria. The default option is SORT_STRING, which sorts the elements as strings. Other options include SORT_REGULAR, SORT_NUMERIC, SORT_LOCALE_STRING, etc.
Here is an example demonstrating how to use the array_unique function:
$numbers = [1, 2, 3, 2, 4, 1, 5];
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);
Output result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 4
[6] => 5
)
It can be seen that the duplicate elements in the original array have been removed, resulting in a new array containing only unique elements.