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

2022-08-30 09:23:13

我需要检查数组中的所有值是否等于同一事物。

例如:

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

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

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


答案 1

所有值都等于测试值:

// note, "count(array_flip($allvalues))" is a tricky but very fast way to count the unique values.
// "end($allvalues)" is a way to get an arbitrary value from an array without needing to know a valid array key. For example, assuming $allvalues[0] exists may not be true.
if (count(array_flip($allvalues)) === 1 && end($allvalues) === 'true') {


}

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

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

}

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

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

/**
 * Checks if an array contains at most 1 distinct value.
 * Optionally, restrict what the 1 distinct value is permitted to be via
 * a user supplied testValue.
 *
 * @param array $arr - Array to check
 * @param null $testValue - Optional value to restrict which distinct value the array is permitted to contain.
 * @return bool - false if the array contains more than 1 distinct value, or contains a value other than your supplied testValue.
 * @assert isHomogenous([]) === true
 * @assert isHomogenous([], 2) === true
 * @assert isHomogenous([2]) === true
 * @assert isHomogenous([2, 3]) === false
 * @assert isHomogenous([2, 2]) === true
 * @assert isHomogenous([2, 2], 2) === true
 * @assert isHomogenous([2, 2], 3) === false
 * @assert isHomogenous([2, 3], 3) === false
 * @assert isHomogenous([null, 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 (that happens to be the first value).
    // 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 : reset($arr);
    foreach ($arr as $val) {
        if ($testValue !== $val) {
            return false;
        }
    }
    return true;
}

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

我的前2个解决方案回答了#2。我的函数回答 #1,或者 #2(如果你把它传递给 2nd arg)。isHomogenous()


答案 2

为什么不在打电话后比较计数?array_unique()

要检查数组中的所有元素是否相同,应像以下内容一样简单:

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

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