简体   繁体   English

PHP:如果为空,如何调节max(array_filter)和min(array_filter)

[英]PHP: how to condition max(array_filter) & min(array_filter) if empty

I have created an array using compact: 我已经使用紧凑创建了一个数组:

$rank_month = compact('jan','feb','mar'); Like this and the data will be fetch using queries and due to that the data will sometimes will be empty and the data will be numbers. 这样,将使用查询来获取数据,并且由于该数据有时将为并且数据将为数字。 And then I'm using the max(array_filter) and min(array_filter) to get the highest and lowest in the array but when the query is empty I get the 然后我使用max(array_filter) and min(array_filter)获得数组中的最高和最低值,但是当查询为空时,我得到了

ERROR: max(): Array must contain at least one element 错误:max():数组必须包含至少一个元素

ERROR: Min(): Array must contain at least one element 错误:Min():数组必须包含至少一个元素

is it possible to condition it like: 是否有可能像这样调节它:

     if(empty(max(array_filter('$rank_month')))){
        $high = ""; }
    else{
    $high = max(array_filter('$rank_month'
}

or is their any way to fix this error? 还是他们有什么办法可以解决此错误? Even if the data is empty 即使数据为空

Thanks. 谢谢。

You are passing array_filter a string when it actually wants an array . 当它实际需要数组时,您正在传递array_filter一个字符串 '$rank_month' is an 11-character string, it's not an array. '$rank_month'是一个11个字符的字符串,不是数组。

You want to make sure you pass the array to array_filter (as well as min and max ). 您要确保将数组传递给array_filter (以及minmax )。

You also want to be checking the length of the filtered array before calling min / max . 您还希望在调用min / max之前检查已过滤数组的长度。

$filtered_month = array_filter($rank_month);
if(!empty($filtered_month)){
    $high = max($filtered_month);
}
else{
    $high = '';
}

simply what the error says: $rank_month is an empty array use sizeof or count 错误简单地说:$ rank_month是一个空数组,使用sizeofcount

if (sizeof($rank_month) > 1) {
    $high = max($rank_month);
} else {
   ...
}

Or 要么

if (count($rank_month) > 1) {
     $high = max($rank_month);
 else {
  ...
}

You need to check if the Array is empty, not if the max value is empty. 您需要检查Array是否为空,而不是max是否为空。 You also don't need to pass in array_filter , the array itself should work. 您也不需要传入array_filter ,数组本身应该可以工作。

if(empty($rank_month)){
    $high = ""; 
} else {
    $high = max($rank_month);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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