PHP min($footage) bringing the wrong value

Asked

Viewed 40 times

2

I have a variable $footage that in 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 used min($footage), no min, brought the 111,5, but in the min brought 90,8. I believe I’m doing wrong.

  • Enter the code you tested. Note that php only considers the number until the comma and what comes after is ignored.

  • 1

    Its values are strings soon min finds the smallest alphabetically, which is the 111,5

  • @Isac I would have to convert the string into another format?

  • Yes, for a numerical type, since it wants to compare them numerically.

1 answer

1


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

To get the minimum in numerical terms you have to convert each value into number. But in your case you still have the detail of , which will not be interpreted as decimal separator, and which can be bypassed by replacing , for . through function str_replace.

The iteration over each element of the array to make the conversion can be done with array_map, that gets 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 clear the difference between the two arrays, 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)
}
  • Show worked, but he "rounded up", left min 6 and did with max, gave 111 (without the ,5)

  • @Leandromarzullo That’s because I was wrong and used intval instead of floatval :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.