Check if all values in array are the same

前端 未结 8 855
生来不讨喜
生来不讨喜 2020-12-02 22:17

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

For example:

$allValues = array(
    \'true\',
    \'true\',
    \'true\',
);
         


        
相关标签:
8条回答
  • 2020-12-02 22:33
    $x = 0;
    foreach ($allvalues as $a) {
       if ($a != $checkvalue) {
          $x = 1;
       }
    }
    
    //then check against $x
    if ($x != 0) {
       //not all values are the same
    }
    
    0 讨论(0)
  • 2020-12-02 22:35

    If your array contains actual booleans (or ints) instead of strings, you could use array_sum:

    $allvalues = array(TRUE, TRUE, TRUE);
    if(array_sum($allvalues) == count($allvalues)) {
        echo 'all true';
    } else {
        echo 'some false';
    }
    

    http://codepad.org/FIgomd9X

    This works because TRUE will be evaluated as 1, and FALSE as 0.

    0 讨论(0)
  • 2020-12-02 22:35

    Another option:

    function same($arr) {
        return $arr === array_filter($arr, function ($element) use ($arr) {
            return ($element === $arr[0]);
        });
    }
    

    Usage:

    same(array(true, true, true)); // => true
    
    0 讨论(0)
  • 2020-12-02 22:37

    Why not just compare count after calling array_unique()?

    To check if all elements in an array are the same, should be as simple as:

    $allValuesAreTheSame = (count(array_unique($allvalues)) === 1);
    

    This should work regardless of the type of values in the array.

    0 讨论(0)
  • 2020-12-02 22:42

    Also, you can condense goat's answer in the event it's not a binary:

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

    to

    if (array_unique($allvalues) === array('foobar')) { 
       // all values in array are "foobar"
    }
    
    0 讨论(0)
  • 2020-12-02 22:42

    You can compare min and max... not the fastest way ;p

    $homogenous = ( min($array) === max($array) );
    
    0 讨论(0)
提交回复
热议问题