Home >Backend Development >PHP Problem >How to use php array_unique function?
array_unique() is a built-in function in PHP. The syntax is array_unique(array, sort_flags), which is used to remove duplicate values from an array. If there are multiple elements in the array with the same value, the first occurring element will be retained and other elements with the same value will be removed from the array.
#php array_unique() function how to use?
php The array_unique() function is used to remove duplicate values from an array.
Basic syntax:
array_unique(array , sort_flags)
Parameters:
1, array: required. Specifies an array.
2. Sortingtype: Optional, specifies how to compare array elements/items. Can be used to modify sorting behavior using the following values:
● SORT_STRING - Default value. Compare items as strings.
● SORT_REGULAR - Compares items normally (does not change type)
● SORT_NUMERIC - Compares items numerically.
● SORT_LOCALE_STRING - Compares items as strings based on the current locale (locale) settings.
Return value: The array_unique() function returns the filtered array after removing all duplicates from the array.
Instructions: First sort the values as strings, then only retain the first encountered key name for each value, and then ignore all subsequent key names. This does not mean that the first occurrence of the same value in an unsorted array will be preserved.
Explanation: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2, that is, when the string represents equal At the same time, the first element will be used.
Note: array_unique() does not work with multi-dimensional arrays.
Let’s take a look at how to use the php array_unique() function through an example.
Example 1:
<?php header("content-type:text/html;charset=utf-8"); $a=array("a"=>"php中文网","b"=>"西门","c"=>"php中文网"); print_r(array_unique($a)); ?>
Output:
Array ( [a] => php中文网 [b] => 西门 )
Example 2:
<?php header("content-type:text/html;charset=utf-8"); $b=array("1"=>"php中文网","2"=>"灭绝师太","c"=>"php中文网",'4' => "欧阳克"); print_r(array_unique($b)); ?>
Output:
Array ( [1] => php中文网 [2] => 灭绝师太 [4] => 欧阳克 )
The above is the detailed content of How to use php array_unique function?. For more information, please follow other related articles on the PHP Chinese website!