如何检查是否只有两个特定的值出现在数组中?

时间:2022-05-02 07:40:30

I have an array that could contain any number of values, some of which may recur.

我有一个数组可以包含任意数量的值,其中一些值可能会重复出现。

Example: 1,2,2,5,7,3

例如:1、2、2、5、7、3

How can I write a test in PHP that checks to see if the only values contained in the array are either 1 or 2?

如何在PHP中编写测试,检查数组中包含的值是否为1或2?

So 1,2,2,1,1,1 would return true.

所以1 2 2 1 1 1 1将返回true。

Meanwhile 1,2,3,1,2,1 would return false.

同时,1 2 3 1 2 1将返回false。

4 个解决方案

#1


5  

This seems to work just fine:

这似乎很有效:

function checkArray($a)
{
    return (bool)!count(array_diff($a, array(1,2)));
}

It'll return true if it's just 1s and 2s or false if not

如果它是1和2s,它将返回true;如果不是,它将返回false

#2


0  

    function return_1_or_2($array){
    foreach($array as $a){
    $c = $a-1;
    if($c>1){
    $flag = true;
break;
    }
    }
    if($flag){
    return false;
    }else{
    return true;
    }
    }

please give this a try... you can further optimise this.... but this is just an example...

请试一试……你可以进一步优化这个....但这只是一个例子…

#3


0  

function array_contains_ones_and_twos_only( &$array ){
  foreach ($array as $x)
    if ($x !== 1 && $x !== 2)
      return false;
  return true;
}

#4


0  

function checkarray($array) {
  foreach($array as $a) {
    if ($a != 1 && $a != 2)
      return false;
  }
  return true;
}

#1


5  

This seems to work just fine:

这似乎很有效:

function checkArray($a)
{
    return (bool)!count(array_diff($a, array(1,2)));
}

It'll return true if it's just 1s and 2s or false if not

如果它是1和2s,它将返回true;如果不是,它将返回false

#2


0  

    function return_1_or_2($array){
    foreach($array as $a){
    $c = $a-1;
    if($c>1){
    $flag = true;
break;
    }
    }
    if($flag){
    return false;
    }else{
    return true;
    }
    }

please give this a try... you can further optimise this.... but this is just an example...

请试一试……你可以进一步优化这个....但这只是一个例子…

#3


0  

function array_contains_ones_and_twos_only( &$array ){
  foreach ($array as $x)
    if ($x !== 1 && $x !== 2)
      return false;
  return true;
}

#4


0  

function checkarray($array) {
  foreach($array as $a) {
    if ($a != 1 && $a != 2)
      return false;
  }
  return true;
}