Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAX - 1 php ?? Does it exist?

Tags:

php

max

I tried to get the 2nd highest value from an array and I simply want to know if it is possible to do something like MAX -1 OR I absolutely need to sort by table and the 2nd highest value

private function max_key($array) {
    foreach ($array as $key => $val) {
    if ($val == max($array))  return $key;
    }
    }
like image 272
user1029834 Avatar asked Jan 20 '26 23:01

user1029834


2 Answers

Seems that there is no such standart function(It's too specific).
You may sort and get second value, but it's O(n log n) complexity.

There is O(n) solution

function second_key($array){
    $max=null;
    $second = null;
    foreach($array as $k => $v){
        if(!isset($max) || $v > $array[$max]){
            $second = $max;
            $max = $k;
        }
        elseif(!isset($second) || $v > $array[$second]){
             $second = $k;
        }
    }
    return $second;
}
like image 120
RiaD Avatar answered Jan 22 '26 13:01

RiaD


 $a = Array ( 1, 2, 40 , 100);
 echo max($a) - 1; // definitely not 40

So yes, you'd need to rsort() (built-in PHP function, sorts the array with highest values first), and then take the 2nd value from the list.

Note that e.g. array( 1 , 10 , 5 , 10 ) has second value == first value; if you want the second-largest unique value, run it through array_unique() first.

like image 38
Piskvor left the building Avatar answered Jan 22 '26 13:01

Piskvor left the building