简体   繁体   中英

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

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

if(max($yourArray) < 5) {
  //all values in array are less than 5
}

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
}

Why you don't create your own function?

function allunder5(yourarray) {
   foreach $yourarray as $yournumber {
       if ($yournumber > 5) {
          return false
       }
    }
    return true
}

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.

function checkArray(&$arr, $max){
    foreach($arr as $e){
       if($e>$max){
           return false;
       }
    }
    return true;
}

@Mchl already gave you the most concise and elegant solution, but I spent some minutes to create an ugly one-liner solution and will post my quirky and hackish solution as a curiosity or a warning example.

function arrayContainsValueOverLimit($arr, $limit) {
    return ! array_reduce(
                    array_map(
                        // Closure used with array_map
                        function ($val) use (&$limit) {
                            return $val <= $limit;
                        }, 

                        // Values passed into array_map
                        $arr
                    ), 

                    // Closure used with array_reduce
                    function ($r, $v) {
                        return $r && $v;
                    }, 

                    // Starting value for array_reduce
                    true
                );
}    

var_dump(
    arrayContainsValueOverLimit(
        array(1,1,3,2,1,2,3,2,2,3,3,2,5,1),
        3
    )
);

For more info on PHP closures, consult the Anonymous functions in the PHP manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM