In PHP development, array is a very common data structure. PHP provides various array functions so that developers can process and operate arrays more conveniently. One of them is the array_unique() function. This article will introduce the usage and precautions of this function.
1. Basic usage of array_unique() function
The array_unique() function is used to remove duplicate values in the array and return a new array after deduplication. Its syntax is as follows:
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Among them, $array represents the original array to be deduplicated; $sort_flags is used to control the order of the output array after deduplication, and the default is to sort by string. This function returns a new array and has no effect on the original array.
2. Usage Examples
Example 1: Remove duplicate elements from the numeric array
$arr = array(1,2,2,3,4,5,5); $newArr = array_unique($arr); print_r($newArr);
Running results:
Array ( [0] => 1 [1] => 2 [3] => 3 [4] => 4 [5] => 5 )
As you can see, the function removes Duplicate elements in a numeric array and return a new array.
Example 2: Remove duplicate elements from an associative array
$arr = array( "a" => 1, "b" => 2, "c" => 2, "d" => 3 ); $newArr = array_unique($arr); print_r($newArr);
Running results:
Array ( [a] => 1 [b] => 2 [d] => 3 )
As you can see, the function can also remove duplicate elements from an associative array and return A new associative array. It should be noted that the key name in the returned new array is inherited from the key name corresponding to the first occurrence of the element in the original array.
3. Notes
You need to pay attention to the following points when using this function:
1. This function is applicable to both index arrays and associative arrays.
2. This function will only remove adjacent duplicate elements, that is, it will only remove adjacent identical elements. If there are multiple identical elements in the array but not adjacent, you need to use other functions first, such as The array_slice() function etc. adjust them to be adjacent.
3. This function will delete all identical elements that appear except the first element, and will inherit the key name corresponding to the first element (if it is an associative array).
4. Summary
The array_unique() function is one of the commonly used functions in PHP arrays, used to remove duplicate elements in the array. Using this function can easily remove duplicates and make the code more concise and efficient. It should be noted that this function will only remove adjacent identical elements, and for associative arrays, you need to pay attention to the key name inheritance relationship in the new array. In actual development, this function needs to be used flexibly according to needs.
The above is the detailed content of Complete list of PHP array functions: array_unique(). For more information, please follow other related articles on the PHP Chinese website!