简体   繁体   English

我如何检查数组的所有元素是否相同?

[英]how do i check all elements of an array are the same?

ie, verify 即,验证

$a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1;

but not 但不是

$a[0]=1; $a[0]=2; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1; $a[0]=1;

thanks :) 谢谢 :)

count(array_unique($a)) == 1;

Check if all items are equal to the first item: 检查所有项目是否与第一项相同:

$first = $array[0];
foreach ($array as $a) {
    if ($a != $first) {
        return false;
    }
}
return true;

If you are new to PHP, then it might be easier for you to use it in this way 如果您不熟悉PHP,那么以这种方式使用它可能更容易

function chkArrayUniqueElem($arr) {
    for($i = 0; $i < count($arr); $i++) {
        for($j = 0; $j < count($arr); $j++) {
            if($arr[$i] != $arr[$j]) return false;
        }
    }
    return true;
}

Other variants brought up earlier are more simple in use. 之前提出的其他变体使用起来更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM