Home > OS >  How to select the lowest value from array that's not 0.00?
How to select the lowest value from array that's not 0.00?

Time:10-10

I have a php array $price that returns the following details

array(36) { 
[0]=> string(4) "0.00" 
[1]=> string(6) "219.00" 
[2]=> string(6) "209.00" 
[3]=> string(6) "239.00" 
[4]=> string(4) "0.00" 
[5]=> string(4) "0.00" 
[6]=> string(6) "229.00" 
[7]=> string(4) "0.00" 
[8]=> string(4) "0.00" 
[9]=> string(4) "0.00" 
[10]=> string(4) "0.00" 
[11]=> string(4) "0.00" 
[12]=> string(4) "0.00" 
[13]=> string(4) "0.00" 
[14]=> string(4) "0.00" 
[15]=> string(4) "0.00" 
[16]=> string(4) "0.00" 
[17]=> string(4) "0.00" 
[18]=> string(4) "0.00" 
[19]=> string(4) "0.00" 
[20]=> string(4) "0.00" 
[21]=> string(4) "0.00" 
[22]=> string(4) "0.00" 
[23]=> string(4) "0.00" 
[24]=> string(4) "0.00" 
[25]=> string(4) "0.00" 
[26]=> string(4) "0.00" 
[27]=> string(4) "0.00" 
[28]=> string(4) "0.00" 
[29]=> string(4) "0.00" 
[30]=> string(5) "40.00" 
[31]=> string(5) "45.00" 
[32]=> string(5) "30.00" 
[33]=> string(5) "35.00" 
[34]=> string(5) "42.00" 
[35]=> string(5) "32.00" 
} 

I was wondering if there is a way to pick the lowest price that isn't equal to 0.00?

I tries using the following

echo min(array_filter($price)) . "\n";

But it returns 0.00

is there a way to take the 0.00 out from the filter>

CodePudding user response:

Convert your array values from string into a float data-type and then select the minimum value above zero. You can use array_map() to convert the values and array_filter() to remove "falsey" values including 0 and 0.00

  1. Convert all array values to floating values because the string "0.00" is non-falsey.

    array_map('floatval', $array);
    
  2. Ignore values of zero using array_filter().

    array_filter(array_map('floatval', $array));
    
  3. Select minimum value of this and output.

    print min(array_filter(array_map('floatval', $array)));
    

View example online:

https://onlinephp.io/c/9ca5f

CodePudding user response:

First filter "0.00" by myFilter function, then find min value in array. Try this:

<?php
$price = array("0.00","229.00","5.00","0.00","3.25");
echo min(array_filter($price,"myFilter")) . "\n";
function myFilter($var){
return ($var !== "0.00");
}
?>

                               

CodePudding user response:

Solution with array_reduce.

$min = array_reduce($price,function($carry,$item){
    return $carry > 0 && $carry < $item ? $carry : $item;
});

Demo: https://3v4l.org/CttaX

CodePudding user response:

<?php
$price = [
    "0.00" ,
    "219.00", 
    "209.00",
    "239.00", 
    "0.00", 
    "0.00"
];

print_r($price);

function notequaltozero($var)
{
    return $var!=0;
}

print_r(array_filter($price,"notequaltozero"));

print min(array_filter($price,"notequaltozero"));

output:

Array
(
    [1] => 219.00
    [2] => 209.00
    [3] => 239.00
)
209.00
  • Related