开发者

How to check if two specific values are the only values appearing in an array?

开发者 https://www.devze.com 2023-03-01 05:44 出处:网络
I have an array that could contain any number of values, some of which may recur. Example: 1,2,2,5,7,3

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

Example: 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?

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

Meanwh开发者_如何学运维ile 1,2,3,1,2,1 would return false.


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


    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...


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号