Reputation: 175
I have an array that contains both strings and numeric values, While using this code I keep getting the highest string value, how to get only numeric max values from the array?
$maxprice = max($textpieces);
I have also tried this but this just returns the number of keys in the array
$maxprice = max(array_search($textpieces));
thanks for your help! I have looked but the max function here does not give any information http://php.net/manual/en/function.max.php
I have also looked at this solution Find highest max() of mixed array but is it possible to get it without building an custom function?
Upvotes: 0
Views: 990
Reputation: 254976
$maxprice = max(array_filter($textpieces, 'is_numeric'));
It at first filters only entries that contains digits only (integers) and then extracts max()
from it
The following solution:
$max = array_reduce($textpieces, function($max, $i) {
if (is_numeric($i) && $i > $max) {
return $i;
}
return $max;
});
var_dump($max);
could be a bit more performance (from both CPU and memory perspectives) but is more complicated as well.
Upvotes: 4