min function that ignores negative values in php

落花浮王杯 提交于 2019-12-24 03:45:26

问题


I have three numbers:

$a = 1
$b = 5
$c = 8

I want to find the minimum and I used the PHP min function for that. In this case it will give 1.

But if there is a negative number, like

$a = - 4
$b = 3
$c = 9

now the PHP min() should give $b and not $a, as I just want to compare positive values, which are $b and $c. I want to ignore the negative number.

Is there any way in PHP? I thought I will check if the value is negative or positive and then use min, but I couldn't think of a way how I can pass only the positive values to min().

Or should I just see if it's negative and then make it 0, then do something else?


回答1:


You should simply filter our the negative values first.

This is done easily if you have all of them in an array, e.g.

$a = - 4;
$b = 3;
$c = 9;

$values = array($a, $b, $c);
$values = array_filter($values, function($v) { return $v >= 0; });
$min = min($values);

print_r($min);

The above example uses an anonymous function so it only works in PHP >= 5.3, but you can do the same in earlier versions with

$values = array_filter($values, create_function('$v', 'return $v >= 0;'));

See it in action.




回答2:


$INF=0x7FFFFFFF;

min($a>0?$a:$INF,$b>0?$b:$INF,$c>0?$c:$INF) 

or

min(array_filter(array($a,$b,$c),function($x){
    return $x>0;
}));



回答3:


http://codepad.org/DVgMs7JF

<?
$test = array(-1, 2, 3);

function removeNegative($var)
{
   if ($var > 0)
       return $var;
}

$test2 = array_filter($test, "removeNegative");

var_dump(min($test2));
?>


来源:https://stackoverflow.com/questions/6748836/min-function-that-ignores-negative-values-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!