How can I check all elements of an array are the same?

those. 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;

thank:)

+3
source share
3 answers
count(array_unique($a)) == 1;
+23
source

Make sure that all elements are equal to the first element:

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

If you are new to PHP, it might be easier for you to use it 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 options listed earlier are easier to use.

+2
source

Source: https://habr.com/ru/post/1750814/


All Articles