How is the array_unique function used in PHP?

The array_unique function in PHP is used to eliminate duplicate elements in an array. It takes an array as input and returns a new array containing only unique elements from the original array.

Here is how to use it:

array_unique(array $array, int $flags = SORT_STRING): array

Explanation of Parameters:

  1. $array: the array to be processed
  2. Optional $flags: Optional parameter used to specify the sorting algorithm when comparing elements. Possible values include:

    SORT_STRING: Compare elements as strings (default)
    SORT_REGULAR: Compare elements using the usual method
    SORT_NUMERIC: Compare elements as numbers
    SORT_LOCALE_STRING: Compare strings according to the language rules of the current locale

Return value:

  1. Return a new array that contains only unique elements.

原文:我正在学习汉语,我想找人练习对话。
Paraphrase: I am learning Chinese and looking for someone to practice conversation with.

$array = [1, 2, 2, 3, 4, 4, 5];
$uniqueArray = array_unique($array);
print_r($uniqueArray);

Output:

Array
(
    [0] => 1
    [1] => 2
    [3] => 3
    [4] => 4
    [6] => 5
)

In the example above, duplicates of 2 and 4 are removed from the original array, and a new array containing only unique elements is returned.

bannerAds