In PHP, arrays are a very commonly used data type, and sometimes we need to deduplicate arrays to meet our needs. So, how to remove duplicate arrays in PHP?
1. PHP array deduplication function
PHP provides two functions that can be used to implement array deduplication, namely array_unique() and array_diff_key().
The array_unique() function can remove duplicate values from the array and return a new array.
Sample code:
$arr = array("apple", "banana", "cherry", "cherry", "banana"); $arr = array_unique($arr); print_r($arr);
Output result:
Array ( [0] => apple [1] => banana [2] => cherry )
It can be seen that the array_unique() function successfully removes duplicate elements in the original array.
The array_diff_key() function can compare two arrays and return the key names of the differences between the two arrays.
Sample code:
$array1 = array("a" => "red", "b" => "green", "c" => "blue"); $array2 = array("a" => "red", "b" => "green", "d" => "yellow"); $result = array_diff_key($array1, $array2); print_r($result);
Output result:
Array ( [c] => blue )
In the example, the array_diff_key() function filters out the parts of $array1 that are different from $array2, and returns a new array.
2. Manually implement array deduplication
In addition to using PHP functions, we can also manually implement array deduplication.
Use a for loop and if statement to traverse the array, determine duplicate elements and remove them.
Sample code:
$arr = array(1, 2, 5, 2, 1, 6, 7, 8, 7, 9); $new_arr = array(); for ($i = 0; $i < count($arr); $i++) { if (!in_array($arr[$i], $new_arr)) { $new_arr[] = $arr[$i]; } } print_r($new_arr);
Output result:
Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 6 [4] => 7 [5] => 8 [6] => 9 )
in_array() function determines whether the elements in the original array already appear in the new array, if not, add them into a new array.
Use the array_flip() function to flip the array, remove duplicate key-value pairs and use the array_flip() function to flip the array back.
Sample code:
$arr = array(1, 2, 5, 2, 1, 6, 7, 8, 7, 9); $new_arr = array_flip(array_flip($arr)); print_r($new_arr);
Output result:
Array ( [0] => 1 [1] => 2 [2] => 5 [3] => 6 [4] => 7 [5] => 8 [6] => 9 )
This method does not need to use a loop, just use the array_flip() function twice.
3. Summary
The above are several methods for removing duplicate arrays in PHP. You can choose the corresponding method according to the specific situation. The array_unique() function and array_diff_key() function are PHP's own functions and have relatively high efficiency. Although manual implementation requires a large amount of code, it can be flexibly adjusted and optimized according to the actual situation.
The above is the detailed content of How to remove duplicate arrays in php. For more information, please follow other related articles on the PHP Chinese website!