检查数组中的所有值是否相同 [英] Check if all values in array are the same

查看:136
本文介绍了检查数组中的所有值是否相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

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

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

If every value in the array equals 'true' then I want to echo 'all true'. If any value in the array equals 'false' then I want to echo 'some false'

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

Any idea on how I can do this?

推荐答案

所有值均等于测试值:

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)) {

}

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

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.

如果您不能使用第二种方法,则您的数组非常大,并且数组的内容可能具有大于1的值(特别是如果该值很可能出现在附近)数组的开头),执行以下操作的速度可能比快很多:

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:

/**
 * @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;
}

注意:一些答案​​将原始问题解释为(1)如何检查所有值是否相同,而其他答案则解释为(2)如何检查所有值是否相同,请确保该值等于测试值.您选择的解决方案应牢记这一细节.

Note: Some answers interpret the original question as (1) how to check if all values are the same, while others interpreted it as (2) how to check if all values are the same and make sure that value equals the test value. The solution you choose should be mindful of that detail.

我的前2个解决方案回答了#2.我的isHomogenous()函数回答#1,如果将第二个参数传递给它,则回答#2.

My first 2 solutions answered #2. My isHomogenous() function answers #1, or #2 if you pass it the 2nd arg.

这篇关于检查数组中的所有值是否相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆