Nick Nick - 4 months ago 22
PHP Question

Check if all values in array are the same

I need to check if all values in an array equal the same thing.


$value1 = 'true';
$value2 = 'true';
$value3 = 'true';

$allvalues = array("$value1","$value2","$value3");

If everything in the $allvalues equals 'true' then it would echo 'all true'

If any value in the $allvalues equals 'false' then it would echo 'some false'

Any idea on how I do this?


all values equal the test value

if (count(array_unique($allvalues)) === 1 && end($allvalues) === 'true') {


or just test for the existence of the thing you don't want.

if (in_array('false', $allvalues, true)) {


Prefer the latter method if you're sure that there's only 2 possible values that could be in the array, as it's much more efficient. But if in doubt, a slow program is better than an incorrect program, so use the first method.

If you can't use the second method, your array is very large, and the contents of the array is likely to have more than 1 value(especially if the value is likely to occur near the beginning of the array), it may be much faster to do the following:

function isHomogenous($arr) {
    $firstValue = current($arr);
    foreach ($arr as $val) {
        if ($firstValue !== $val) {
            return false;
    return true;