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.

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

Hubert Kario
  • 21,314
  • 3
  • 24
  • 44
bflora2
  • 733
  • 3
  • 8
  • 26

4 Answers4

6

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

James C
  • 14,047
  • 1
  • 34
  • 43
  • This answer looks cool, BUT array_diff has a complexity of O(2*n) according to http://stackoverflow.com/questions/2473989/list-of-big-o-for-php-functions. – linepogl Apr 26 '11 at 12:45
  • A valid comment but I suspect that unless the array is huge this is going to pale into insignificance to the comparative time of running a MySQL query, etc that the page is likely to be doing too – James C Apr 26 '11 at 12:50
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...

Karthik
  • 1,091
  • 1
  • 13
  • 36
0
function array_contains_ones_and_twos_only( &$array ){
  foreach ($array as $x)
    if ($x !== 1 && $x !== 2)
      return false;
  return true;
}
linepogl
  • 9,147
  • 4
  • 34
  • 45
0
function checkarray($array) {
  foreach($array as $a) {
    if ($a != 1 && $a != 2)
      return false;
  }
  return true;
}
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176