PHP min ($ footage) bringing the wrong value

2

I have a $ variable variable that var_dump brings me:

array(5) {
  [0]=>
  string(5) "111,5"
  [1]=>
  string(2) "81"
  [2]=>
  string(4) "90,8"
  [3]=>
  string(4) "79,6"
  [4]=>
  string(1) "6"
}

I want to bring the minimum and maximum value and I used min ($ footage), in the min, brought the 111.5, but in the min brought 90.8. I think I'm doing it wrong.

    
asked by anonymous 15.06.2018 / 16:30

1 answer

1

Your values are strings, so the result you get is the minimum of an alphabetic sort, which would be 111,5 .

To get the least numeric you have to convert each value into a number. But in your case it still has the detail of , that will not be interpreted as a decimal separator, and you can work around by replacing , with . with the str_replace .

The iteration over each element of the array to do the conversion can be done with array_map , which is shorter and more direct.

Example:

$arr = Array("111,5", "81", "90,8", "79,6", "6");

$arrNumeros = array_map(function($el){
    return floatval(str_replace(',', '.', $el));    
}, $arr);

echo min($arrNumeros); // 6

See this example in Ideone

To make the difference between the two arrays clear, see the result of var_dump($arrNumeros); :

array(5) {
  [0]=>
  float(111.5)
  [1]=>
  float(81)
  [2]=>
  float(90.8)
  [3]=>
  float(79.6)
  [4]=>
  float(6)
}
    
15.06.2018 / 16:46