This is my array
Array ( [0] => $30.00 [1] => $200.00 [2] => $138.00 [3] => $100.00 [4] => $30.00
[5]=>$30.00 [6] => $30.00 )
Trying to get the max and min value from this array
echo $maxprice = max($list);
echo $minprice = min($list);
I get $30.00 for max and $100.00 for min
I am guessing this is due to the values are in money string.
Can someone please tell me how I could get the real max and min for this array? Is this really due to money string?
Thanks in advance
Note This array is stripped down from a multidimensional array. If it was normal array, it would be straightforward
You need to use decimal values (without the "$") in your array. The dollar sign should only be applied when outputting to display.
To get the string converted to floats, you can just array_walk()
the array.
If on PHP 5.3 or greater, I like to use closures like this
array_walk($array, function (&$value, $key) {
$value = (float)ltrim($value, '$');
});
If in older version of PHP, you would need to define a separate function and call the function in array_walk like this
array_walk($array, 'strip_dollar_signs');
function strip_dollar_signs (&$value, $key) {
$value = (float)ltrim($value, '$');
}
Then just sort your array as you typically would
sort($array, SORT_NUMERIC);
Remove the '$' sign to make sure php treats the values as numbers
consider storing numeric values only, unless you work with more than one currency. this code should get you minimum and maximum
$copy = $list;
foreach($copy as $key=>$value)$copy[$key] = str_replace('$', '', $value);
echo $maxprice = max($copy);
echo $minprice = min($copy);