PHP: Check to see if all the values in an array ar

2020-08-23 06:47发布

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

标签: php arrays
6条回答
Summer. ? 凉城
2楼-- · 2020-08-23 06:49

Why you don't create your own function?

function allunder5(yourarray) {
   foreach $yourarray as $yournumber {
       if ($yournumber > 5) {
          return false
       }
    }
    return true
}
查看更多
爷、活的狠高调
3楼-- · 2020-08-23 06:54

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
}
查看更多
成全新的幸福
4楼-- · 2020-08-23 06:57

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

查看更多
孤傲高冷的网名
5楼-- · 2020-08-23 07:03
function checkArray(&$arr, $max){
    foreach($arr as $e){
       if($e>$max){
           return false;
       }
    }
    return true;
}
查看更多
家丑人穷心不美
6楼-- · 2020-08-23 07:04

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.

查看更多
太酷不给撩
7楼-- · 2020-08-23 07:13
if(max($yourArray) < 5) {
  //all values in array are less than 5
}
查看更多
登录 后发表回答