php:检查数组是否有重复项 [英] php: check if an array has duplicates
问题描述
我确定这是一个非常明显的问题,并且有一个函数可以做到这一点,但我似乎找不到它.在 PHP 中,我想尽可能有效地知道我的数组中是否有重复项.我不想像 array_unique
那样删除它们,我也不想特别想运行 array_unique
并将其与原始数组进行比较以查看它们是否是一样,因为这似乎非常低效.就性能而言,预期条件"是数组没有重复项.
I'm sure this is an extremely obvious question, and that there's a function that does exactly this, but I can't seem to find it. In PHP, I'd like to know if my array has duplicates in it, as efficiently as possible. I don't want to remove them like array_unique
does, and I don't particularly want to run array_unique
and compare it to the original array to see if they're the same, as this seems very inefficient. As far as performance is concerned, the "expected condition" is that the array has no duplicates.
我只是想做一些类似的事情
I'd just like to be able to do something like
if (no_dupes($array))
// this deals with arrays without duplicates
else
// this deals with arrays with duplicates
有什么明显的功能我没有想到吗?
如何检测 PHP 数组中的重复值?
有正确的标题,是一个非常相似的问题,但是如果你真的阅读了这个问题,他正在寻找 array_count_values.
Is there any obvious function I'm not thinking of?
How to detect duplicate values in PHP array?
has the right title, and is a very similar question, however if you actually read the question, he's looking for array_count_values.
推荐答案
您可以:
function has_dupes($array) {
$dupe_array = array();
foreach ($array as $val) {
if (++$dupe_array[$val] > 1) {
return true;
}
}
return false;
}
这篇关于php:检查数组是否有重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!