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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10560658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:28:15  来源:igfitidea点击:

Check if all values in array are the same

phparrays

提问by Nick

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

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

For example:

例如:

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

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'

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

Any idea on how I can do this?

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

回答by goat

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.

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

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

如果不能用第二种方法,你的数组很大,而且数组的内容很可能有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;
}

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 andmake sure that value equals the test value. The solution you choose should be mindful of that detail.

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

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

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

回答by bfavaretto

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

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

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

http://codepad.org/FIgomd9X

http://codepad.org/FIgomd9X

This works because TRUEwill be evaluated as 1, and FALSEas 0.

这工作,因为TRUE会进行评估 1,并FALSE作为0

回答by user1718888

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"
}

回答by Werner

Why not just compare count after calling array_unique()?

为什么不只是在调用后比较计数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.

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

回答by quazardous

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

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

$homogenous = ( min($array) === max($array) );

回答by Wayne

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

回答by octern

$alltrue = 1;
foreach($array as $item) {
    if($item!='true') { $alltrue = 0; }
}
if($alltrue) { echo("all true."); }
else { echo("some false."); }

Technically this doesn't test for "some false," it tests for "not all true." But it sounds like you're pretty sure that the only values you'll get are 'true' and 'false'.

从技术上讲,这不会测试“某些错误”,而是测试“并非全部正确”。但听起来您很确定您将获得的唯一值是“真”和“假”。

回答by Norse

$x = 0;
foreach ($allvalues as $a) {
   if ($a != $checkvalue) {
      $x = 1;
   }
}

//then check against $x
if ($x != 0) {
   //not all values are the same
}