In PHP development, array (Array) is an inevitable data type. It can store multiple values or strings and perform corresponding operations. However, during the development process, we sometimes need to deduplicate the array, that is, remove duplicate elements. This article will introduce how to remove duplicate elements from PHP arrays.
Method 1: Use array_unique() function
PHP’s built-in function array_unique() can easily remove duplicate elements from an array. This function keeps the first occurrence of the element and removes subsequent duplicate elements.
Syntax: array_unique(array);
Sample code:
$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry"); print_r(array_unique($names));
Output result:
Array ( [0] => Tom [1] => Jerry [3] => Peter )
Method 2: Use loop traversal
Another method is to use a loop to traverse the array. Whenever a new element is encountered, determine whether the element already exists in the new array. If it does not exist, add it to the new array.
Sample code:
$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry"); $new_names = array(); foreach ($names as $name) { if (!in_array($name, $new_names)) { $new_names[] = $name; } } print_r($new_names);
Output result:
Array ( [0] => Tom [1] => Jerry [3] => Peter )
Method 3: Use the array_flip() function
array_flip() function can convert the keys in the array and values are interchanged, therefore, duplicate elements in the array can be removed through the array_flip() and array_keys() functions.
Sample code:
$names = array("Tom", "Jerry", "Tom", "Peter", "Jerry"); $new_names = array_flip(array_keys(array_flip($names))); print_r($new_names);
Output result:
Array ( [0] => Tom [1] => Jerry [3] => Peter )
The above three methods can effectively remove duplicate elements in PHP arrays. Which method to use depends on the actual situation.
The above is the detailed content of How to remove duplicate elements from PHP array. For more information, please follow other related articles on the PHP Chinese website!