How to delete the same elements in a php array: 1. Use the array_unique() function; 2. Use the foreach loop and the in_array() function; 3. Use the array_flip() and array_values() functions.
PHP array is a very convenient data structure that allows us to store and operate multiple data elements. Sometimes we may need to remove identical elements from an array to ensure that the array only contains unique elements. This article will introduce several methods you can use to delete identical elements.
1. Use array_unique() function
PHP提供了一个内置函数array_unique(),它可以用来删除数组中的重复元素。该函数会返回一个新的数组,其中只包含唯一的元素。 $original_array=array("apple","banana","apple","orange","banana"); $unique_array=array_unique($original_array); print_r($unique_array);
Output result:
Array ( [0]=>apple [1]=>banana [3]=>orange )
2. Use foreach loop and in_array() function
We can also use The foreach loop and in_array() function are used to traverse the array and remove duplicate elements by determining whether the element already exists. If it already exists, we can use the unset() function to delete the element.
$original_array=array("apple","banana","apple","orange","banana"); $unique_array=array(); foreach($original_arrayas$element){ if(!in_array($element,$unique_array)){ $unique_array[]=$element; } } print_r($unique_array);
Output result:
Array ( [0]=>apple [1]=>banana [3]=>orange )
3. Use array_flip() and array_values() functions
We can also use array_flip() and array_values() functions to delete duplicate elements . First use the array_flip() function to swap the keys and values of the array so that duplicate values are overwritten, and finally use the array_values() function to re-index the array.
$original_array=array("apple","banana","apple","orange","banana"); $unique_array=array_flip($original_array); $unique_array=array_values($unique_array); print_r($unique_array);
Output results:
Array ( [0]=>apple [1]=>banana [2]=>orange )
These methods can be selected and used according to personal needs and preferences. Whichever method you choose, you can effectively remove identical elements from the array, ensuring that the array contains only unique elements. When processing data, it is very important to ensure that there are no duplicate elements in the array to avoid data redundancy and errors. .
The above is the detailed content of How to delete the same elements in php array. For more information, please follow other related articles on the PHP Chinese website!