Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Check to see if all the values in an array are less than x

Tags:

arrays

php

Is there a function to do this?

For example if I have an array like 1,1,3,2,1,2,3,2,2,3,3,2,5,1 The function should return true if and only if all the numbers in the array are less than 5

like image 531
dukevin Avatar asked Aug 09 '11 07:08

dukevin


4 Answers

array_map that everyone is suggesting is of not much use here. array_reduce would be:

array_reduce($array, function ($v, $a) { return $v && $a < 5; }, true)

But @Mchl's use of max is of course best.

like image 71
deceze Avatar answered Nov 13 '22 04:11

deceze


if(max($yourArray) < 5) {
  //all values in array are less than 5
}
like image 24
Mchl Avatar answered Nov 13 '22 06:11

Mchl


You could use array_filter to run a command over each argument, and ensure that the list is empty, like so:

function greater_than_four($num) {
    return (int)$num > 4;
}

if( array_filter($list, "greater_than_four") ) {
    // INVALID
} else {
    // VALID
}
like image 2
OverZealous Avatar answered Nov 13 '22 04:11

OverZealous


Why you don't create your own function?

function allunder5(yourarray) {
   foreach $yourarray as $yournumber {
       if ($yournumber > 5) {
          return false
       }
    }
    return true
}
like image 2
Samy Zine Avatar answered Nov 13 '22 05:11

Samy Zine