How to find the duplicate and highest value in an array
I have an array like this
array={'a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2'};
The array value might be differe开发者_运维技巧nt depending on the $_POST variables. My question is how to find the highest value in my array and return the index key. In my case, I need to get 'c' and 'd' and the value of 6. Not sure how to do this. Any helps would be appreciated. Thanks.
$max = max(array_values($array));
$keys = array_keys($array, $max);
Have a look at arsort which will sort an array in reverse order and maintain index association. So:
arsort($array);
This will end up with the largest values at the top of the array. Depending on what you need array_unique can remove duplicate values from your array.
$array = array(
'key1' => 22,
'key2' => 17,
'key3' => 19,
'key4' => 21,
'key5' => 24,
'key6' => 8,
);
function getHighest($array)
{
$highest = 0;
foreach($array as $index => $value)
{
if(is_numeric($value) && $value > $highest)
{
$highest = $index;
}
}
return $highest;
}
echo getHighest($array); //key5
Or this should do the magic, it would probably be faster than php built-in functions
$maxValue = -1;
$max = array();
foreach ($items as $key => $item) {
if ($item == $maxValue) {
$max[] = $key;
} elseif ($item > $maxValue) {
$max = array();
$max[] = $key;
$maxValue = $item;
}
}
精彩评论