检查数组中的所有值是否相同

Nic*_*ick 49 php arrays

我需要检查数组中的所有值是否相同.

例如:

$allValues = array(
    'true',
    'true',
    'true',
);
Run Code Online (Sandbox Code Playgroud)

如果数组中的每个值都等于'true'那么我想要回显'all true'.如果数组中的任何值等于,'false'那么我想回显'some false'

有关如何做到这一点的任何想法?

goa*_*oat 112

所有值都等于测试值

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


}
Run Code Online (Sandbox Code Playgroud)

或者只测试你不想要的东西的存在.

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

}
Run Code Online (Sandbox Code Playgroud)

如果您确定数组中只有2个可能的值,则更喜欢后一种方法,因为它更有效.但如果有疑问,慢程序比不正确的程序更好,所以使用第一种方法.

如果你不能使用第二种方法,你的数组非常大,并且数组的内容可能有超过1的值(特别是如果值可能发生在数组的开头附近),它可能是执行以下操作快得多:

/**
 * @param array $arr
 * @param null  $testValue
 * @return bool
 * @assert isHomogenous([]) === true
 * @assert isHomogenous([2]) === true
 * @assert isHomogenous([2, 2]) === true
 * @assert isHomogenous([2, 2], 2) === true
 * @assert isHomogenous([2, 2], 3) === false
 * @assert isHomogenous([null, null]) === true
 */
function isHomogenous(array $arr, $testValue = null) {
    // If they did not pass the 2nd func argument, then we will use an arbitrary value in the $arr.
    // By using func_num_args() to test for this, we can properly support testing for an array filled with nulls, if desired.
    // ie isHomogenous([null, null], null) === true
    $testValue = func_num_args() > 1 ? $testValue : current($arr);
    foreach ($arr as $val) {
        if ($testValue !== $val) {
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

*注意 - 有些答案将原始问题解释为1)isHomogenous(),而其他答案则将其解释为2)isHomogenous().您选择的解决方案应该注意细节.我的前两个解决方案回答了#2.我的isHomogenous()函数回答#1,虽然您可以通过传入值isHomogenous()作为测试值来修改它来回答#2 ,而不是像我那样使用数组中找到的第一个值.

  • 喜欢后面的部分...检查错误而不是真..超高效...... (6认同)
  • 为什么我们需要这部分?"结束($ allvalues)==='true'"有人可以解释一下吗? (2认同)

bfa*_*tto 14

如果你的数组包含实际的布尔值(或整数)而不是字符串,你可以使用array_sum:

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

http://codepad.org/FIgomd9X

这工作,因为TRUE会被评价为 1,和FALSE作为0.


小智 12

此外,如果不是二元的话,你可以压缩山羊的答案:

if (count(array_unique($allvalues)) === 1 && end($allvalues) === 'true') {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

if (array_unique($allvalues) === array('foobar')) { 
   // all values in array are "foobar"
}
Run Code Online (Sandbox Code Playgroud)


Wer*_*ner 7

为什么不在调用后比较计数array_unique()

要检查数组中的所有元素是否相同,应该如下所示:

$allValuesAreTheSame = (count(array_unique($allvalues)) === 1);
Run Code Online (Sandbox Code Playgroud)

无论数组中的值类型如何,这都应该有效.


qua*_*ous 5

您可以比较最小值和最大值...不是最快的方法;p

$homogenous = ( min($array) === max($array) );
Run Code Online (Sandbox Code Playgroud)