简体   繁体   English

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

[英]Check if all values in array are the same

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' .如果数组中的每个值都等于'true'那么我想回显'all true' If any value in the array equals 'false' then I want to echo 'some false'如果数组中的任何值等于'false'那么我想回显'some false'

Any idea on how I can do this?关于如何做到这一点的任何想法?

All values equal the test value:所有值均等于测试值:

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


}

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.如果您确定数组中只有 2 个可能的值,则更喜欢后一种方法,因为它效率更高。 But if in doubt, a slow program is better than an incorrect program, so use the first method.但如果有疑问,慢程序比不正确的程序要好,所以使用第一种方法。

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 2nd value is likely to occur near the beginning of the array), it may be much faster to do the following:如果不能使用第二种方法,你的数组很大,而且数组的内容很可能有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;
}

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.注意:一些答案将原始问题解释为 (1) 如何检查所有值是否相同,而其他答案将其解释为 (2) 如何检查所有值是否相同确保该值等于测试值。 The solution you choose should be mindful of that detail.您选择的解决方案应该注意这个细节。

My first 2 solutions answered #2.我的前 2 个解决方案回答了 #2。 My isHomogenous() function answers #1, or #2 if you pass it the 2nd arg.我的isHomogenous()函数会回答 #1,如果您将第二个参数传递给它,则会回答 #2。

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.无论数组中的值的类型如何,这都应该有效。

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

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 TRUE will be evaluated as 1 , and FALSE as 0 .这是有效的,因为TRUE将被评估为1FALSE将被评估为0

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

$homogenous = ( min($array) === max($array) );
$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'.但听起来您很确定您将获得的唯一值是“真”和“假”。

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

Answering my method for people searching in 2023.回答我在 2023 年搜索人员的方法。

$arr = [5,5,5,5,5];
$flag = 0;
$firstElement = $arr[0];

foreach($arr as $val){
    // CHECK IF THE FIRST ELEMENT DIFFERS FROM ANY OTHER ELEMENT IN THE ARRAY
    if($firstElement != $val){
        // FIRST MISMATCH FOUND. UPDATE FLAG VALUE AND BREAK OUT OF THE LOOP.
        $flag = 1;
        break;
    }
}

if($flag == 0){
    // ALL THE ELEMENTS ARE SAME... DO SOMETHING
}else{
    // ALL THE ELEMENTS ARE NOT SAME... DO SOMETHING
}

In an array where all elements are same, it should always be true that all the elements MUST match with the first element of the array.在所有元素都相同的数组中,所有元素必须与数组的第一个元素匹配始终为真。 Keeping this logic in mind, we can get the first element of the array and iterate through each element in the array to check for that first element in the loop which does not match with the first element in the array.记住这个逻辑,我们可以获取数组的第一个元素并遍历数组中的每个元素以检查循环中与数组中的第一个元素不匹配的第一个元素。 If found, we will change the flag value and break out of the loop immediately.如果找到,我们将更改标志值并立即跳出循环。 Else, the loop will continue till it reaches the end.否则,循环将继续,直到它到达终点。 Later, outside the loop, we can use this flag value to determine if all the elements in the array are same or not.稍后,在循环外,我们可以使用此标志值来确定数组中的所有元素是否相同。

This solution is good for arrays with definite limit of elements (small array).此解决方案适用于具有明确元素限制(小数组)的 arrays。 However, I am not sure how good this solution would be for arrays with very large number of elements present considering that we are looping through each and every element to check for the first break even point.但是,我不确定这个解决方案对于 arrays 有多好,因为我们正在遍历每个元素以检查第一个收支平衡点。 Please use this solution at your own convenience and judgement.请根据您自己的方便和判断使用此解决方案。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM