Home > Article > Backend Development > What built-in functions are available for PHP array deduplication?
PHP provides a variety of built-in functions for array deduplication, including: array_unique(): retain unique elements and return a new array. array_intersect_key(): Cross-compare keys, retaining only the values corresponding to keys that exist in the first array. array_unique() array_values(): Remove duplicates first, then re-index, retaining only unique elements.
PHP Array Deduplication Built-in Function Guide
In PHP, deduplicating arrays is a common task. PHP provides a variety of built-in functions to help you accomplish this task easily and efficiently.
1. array_unique() function
array_unique()
The function deduplicates an array by retaining the unique elements in the array. It returns a new array containing the deduplicated elements.
<?php $array = ['foo', 'bar', 'baz', 'foo', 'bar']; $uniqueArray = array_unique($array);
Output:
Array ( [0] => foo [1] => bar [2] => baz )
2. array_intersect_key() function
array_intersect_key()
Function combines the keys of multiple arrays Cross comparison, retaining only the values corresponding to keys that exist in the first array. This effectively deduplicates the array.
<?php $array1 = ['foo' => 1, 'bar' => 2, 'baz' => 3]; $array2 = ['foo' => 4, 'baz' => 5]; $uniqueArray = array_intersect_key($array1, $array2);
Output:
Array ( [foo] => 1 [baz] => 3 )
3. array_unique() array_values() function
array_unique()
function and array_values()
functions can also be used in combination to deduplicate arrays. array_unique()
The function first removes duplicate elements, and then the array_values()
function re-indexes the array, retaining only unique elements.
<?php $array = ['foo', 'bar', 'baz', 'foo', 'bar']; $uniqueArray = array_values(array_unique($array));
Output:
Array ( [0] => foo [1] => bar [2] => baz )
Practical case
The following is a practical case demonstrating how to use array_unique()# in a Web application ## Functions to deduplicate user input:
<?php // 获取用户输入 $userInput = $_POST['user_input']; // 将用户输入转换为数组 $array = explode(",", $userInput); // 对数组进行去重 $uniqueArray = array_unique($array); // 保存去重后的数组 // ...Using these built-in functions, you can easily and efficiently deduplicate PHP arrays, simplifying your code and improving performance.
The above is the detailed content of What built-in functions are available for PHP array deduplication?. For more information, please follow other related articles on the PHP Chinese website!