The best way to check if all table values ​​are within a range

advertisements

How is best way to check if all array values are in range?

For example:

$range = range(10, 40);

$array1 = array(10, 20, 40); // OK
$array2 = array(11, 22, 42, 30); // FALSE
$array3 = array(50); // OK
$array4 = array(10, 20, 30, 'a'); // FALSE
$array5 = array("%", 20); // FALSE
$array6 = array(10, 20, 40, 39, 40); // OK

So how can I check if array values are numbers (integer) and are in range?

I tried:

$tmp = 0;
foreach ($array1 as $a1) {
   if (!in_array($a1, $range) && is_int($a1)) {
      $tmp++;
   }
}

if ($tmp > 0) {
   echo "false";
} else {
echo "ok";
}

Maybe is better way? Maybe with array_map()?


    <?php
    $range      = range(10, 40);
    $array1     = array(10, 20, 40);
    $isInRange  = (min($array1)>=min($range) and max($array1)<=max($range)) ? "Yes" : "No";
    echo $isInRange;
    //prints 'Yes' when compared with array(10, 20, 40);
    //prints 'No' when compared with array(11, 22, 42, 30); as you have out range value 42 here
    ?>

A simplest way to check this is using max and min here, because you avoid validating for integers here. max selects the maximum value within the array, and min the least one.