简体   繁体   English

PHP在数组中找到正值和负值的最大值

[英]php find max value for both positive and negative value in array

I have an array i want to find max value for both positive and negative value. 我有一个数组,我想找到正值和负值的最大值。 The expected result would be -13.2 and 7.8 预期结果将是-13.2和7.8

$array = array
(
    [0] => -13.2
    [1] => -14.5
    [2] => -14.3
    [3] => -13.7
    [4] => -13.8
    [5] => -14.6
    [6] => 6.4
    [7] => 6.9
    [8] => 7.2
    [9] => 6.9
    [10] => 7.8
    [11] => 6.9
    [12] => 6.3
    [13] => 7.2
    [14] => 6.9
    [15] => 6.8
)

$maxrl='';
for($i=1,$j=0;$i<=count($array);$i++,$j++)
    {
        if($maxr <= $array[$j])
            {
                if(($maxr < $array[$j]) && ($maxrl != ''))
                    {
                        $maxrl='';
                        $maxrl.="L".$k.",";
                    }
                else
                    {
                        $maxrl.="L".$k.",";
                    }
                $maxr = $max_array[$j];

            }
        $k++;
    }
echo "<tr><td >'.$maxr.'</td><td>'.substr($maxrl,0,-1).'</td><>/tr>";

You can simply use max & min functions, 您可以简单地使用max和min函数,

echo "Max Value:- ".max($array); // Max Value:-  7.8
echo "Min Value:- ".min($array); // Min Value:- -14.6

UPDATED: If you really want max from both negative & positive values, 更新:如果您确实想同时从负值和正值中获得最大值,

$positive = array_filter($array, function ($v) {
  return $v > 0;
});

$negative = array_filter($array, function ($v) {
  return $v < 0;
});

echo "Max in positive Value:- ".max($positive); // Max in positive Value:-  7.8
echo "Min in negative Value:- ".min($negative); // Max in negative Value:- -13.2

For the positive maximum just take 对于正的最大值,只需

$max = max($array);

The highest minimum is a bit more complex: 最高的最低要求稍微复杂一点:

$minArray = array();
foreach ( $array as $val )
    if ( $val < 0 )
       $minArray[] = $val;

$min = max($minArray);

If I get the OPs question right 如果我正确回答了运营问题

PHP has max and min methods specifically for this PHP有专门用于此的maxmin方法

$max = max($array); // 7.8
$min = min($array); // -14.6
//$dd = array(-50, -25, -5, -80, -40, -152, -45, -28, -455, -100, -98, -455);
$dd = array(50, -25, -5, 80, -40, -152, -45, 28, -455, 100, 98, -455);
//$dd = array(50, 25, 5, 80, 40, 152, 45, 28, 455, 100, 98, 455);
$curr = '';
$max = $dd[0];

for($i = 0; $i < count($dd); $i++) {
    $curr = $dd[$i];

    if($curr >= $max) {
        $max = $curr;   
    }
}

echo "greatest number is $max";

Just do: 做就是了:

$max = max($array);
$min = min($array);

Much easier! 容易得多! ;) ;)

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

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