Home >Backend Development >PHP Problem >How to remove duplicate elements from an array in php
php method to remove duplicate elements in an array: first create a PHP sample file; then define an "array_remove_value" method; then delete it through unset and other functions; finally use the key before deleting the array to operate the corresponding Just value.
Recommended: "PHP Tutorial"
Method 1. Completely delete duplicate array instances-----Delete An element in the array
function array_remove_value(&$arr, $var){ foreach ($arr as $key => $value) { if (is_array($value)) { array_remove_value($arr[$key], $var); } else { $value = trim($value); if ($value == $var) { unset($arr[$key]); } else { $arr[$key] = $value; } } } }
$a is an array:
count($a); //得到4 unset($a[1]); //删除第二个元素 count($a); //得到3 echo $a[2]; //数组中仅有三个元素,本想得到最后一个元素,但却得到blue, echo $a[1]; //无值 ?>
That is to say, after deleting the elements in the array, the number of elements in the array (obtained with count()) becomes , but the array subscripts are not rearranged, and the corresponding value must be manipulated using the key before deleting the array.
Later I adopted another method. In fact, it was not called a "method" at all. I used the ready-made function array_splice() in php4.
count ($a); //得到4 array_splice($a,1,1); //删除第二个元素 count ($a); //得到3 echo $a[2]; //得到yellow echo $a[1]; //得到blue ?>
Method 2. Function to delete duplicate elements in an array
function delmember(&$array, $id) { $size = count($array); for($i = 0; $i <$size - $id - 1; $i ++) { $array[$id + $i] = $array[$id + $i + 1]; } unset($array[$size - 1]); }
The above is the detailed content of How to remove duplicate elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!