Home > Article > Backend Development > Remove duplicate elements from array in PHP
This article introduces the content of deleting duplicate elements of arrays in PHP. It has certain reference value. Now I share it with you. Friends in need can refer to it.
Several methods of deleting array elements in PHP are here In many cases, our arrays will be duplicated. So what should we do if we delete some duplicate contents in the array? These elements must remain unique, so we try to find a way to delete them. The following uses a traversal query to delete several duplicate array elements. method.
Method 1. Completely delete duplicate array instances-----Delete one element in the array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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:
##?
2 3 4 5 6 |
count($a); //得到4 unset($a[1]); //删除第二个元素 count($a); //得到3 echo $a[2]; //数组中仅有三个元素,本想得到最后一个元素,但却得到blue, echo $a[1]; //无值 ?> |
function array_splice()
in php4.
3 4 5 6
|
| ##Method 2,
# #?
456789
## 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]); } |
补充小例子: 方法一、php有内置函数array_unique可以用来删除数组中的重复值
注意键名保留不变。array_unique() 先将值作为字符串排序,然后对每个值只保留第一个遇到的键名,接着忽略所有后面的键名。这并不意味着在未排序的 array 中同一个值的第一个出现的键名会被保留。
上例将输出:
方法二、array_flip实现去重效果 另一个方法是使用php的array_flip函数来间接的实现去重效果
二种方法不同的是用array_flip得到的是重复元素最后的键和值,用array_unique得到的是二个重复元素第一个键和值。 希望本文所述对大家学习php程序设计有所帮助,解决数组重复元素问题。 相关推荐: |
The above is the detailed content of Remove duplicate elements from array in PHP. For more information, please follow other related articles on the PHP Chinese website!