如何检测PHP数组中的重复值? [英] How to detect duplicate values in PHP array?
本文介绍了如何检测PHP数组中的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 PHP 中的一维数组.我想检测重复值的存在,然后计算重复值的数量并输出结果.例如,给定以下数组:
I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and out put the results. For example, given the following array:
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');
我想打印:
apple (2)
orange
pear (2)
banana
kiwi (3)
关于如何解决这个问题有什么建议吗?
Any advice on how to approach this problem?
谢谢.
迈克
推荐答案
您可以使用 array_count_values 函数
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');
print_r(array_count_values($array));
会输出
Array
(
[apple] => 2
[orange] => 1
[pear] => 2
etc...
)
这篇关于如何检测PHP数组中的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文