php - Find the second highest variable in array -
i find second highest variable in array.
for example if have:
$cookies = array( "chocolate" => "20", "vanilla" => "14", "strawberry" => "18", "raspberry" => "19", "bluebery" => "29" ); i can use max($cookies) find highest variable, "bluebery" => "29".
but how find second highest? "chocolate" => "20"
sort , second item easiest way:
arsort($cookies); $keys = array_keys($cookies); echo $keys[1]; // chocolate echo $cookies[$keys[1]]; // 20 if want more efficient way, can manually, keeping track of both highest , second-highest items @ same time:
function secondmax($arr) { $max = $second = 0; $maxkey = $secondkey = null; foreach($arr $key => $value) { if($value > $max) { $second = $max; $secondkey = $maxkey; $max = $value; $maxkey = $key; } elseif($value > $second) { $second = $value; $secondkey = $key; } } return array($secondkey, $second); } usage:
$second = secondmax($cookies); echo "{$second[0]} => {$second[1]}"; // chocolate => 20
Comments
Post a Comment