开发者

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜