PHP 检查数组值是否唯一

PHP check if array value is unique

我今天早些时候在做一些事情,我偶然发现了这个问题。如何检查某个数组值在该数组中是否唯一?

$array = array(1, 2, 3, 3, 4, 5);

if(unique_in_array($array, 1)) //true
if(unique_in_array($array, 3)) //false

我一直在考虑使用 array_search() or in_array(),但两者都不是非常有用的查找重复项。我确定我可以编写这样的函数来完成它:

function unique_in_array($arr, $search){
    $found = 0;

    foreach($arr as $val){
        if($search == $val){
            $found++;
        }
    }

    if($found > 1){
        return true;
    } else {
        return false;
    }
}

或者另一个解决方案是像这样使用 array_count_values()

$array_val_count = array_count_values($array);

if($array_val_count[$search] > 1){
    return true;
} else {
    return false;
}

但我觉得 PHP 没有内置功能(或至少是更好的方法)来做到这一点,这对我来说似乎很奇怪?

试试这个:

if (1 === count(array_keys($values, $value))) {
    // $value is unique in array
}

参考:

You can try like this -

$array1   = array(1, 2, 3, 3, 4, 3, 3, 5);

$func   = array_count_values($array1);
$count  = $func[3];  #Pass value here

echo $count;  #this will echo 4

#If you pass undefined value, You should use like as below
$count = isset($func[8])? $func[8] : 0;

echo $count;  #this will echo 0, Because 8 is absent in $array1

这里是array_count_values()

的函数参考

我发现这个可以检查数组是否有重复值

$array = array(1, 2, 3, 3, 4, 5);

if(count(array_unique($array)) != count($array)){
    // Return true Array is unique
}
else{
    // Return false Array is not unique
}