0

how to find third maximum number from a number column(any table) in php? What is the query?

i got this question in interview.

30th May 2017, 9:18 PM
Monami
Monami - avatar
1 Antwort
0
If you are asking about PHP arrays (not SQL table query), and the presupposition is that values in array can repeat (the array has non-unique values), then: <?php $ar = array( 1,4,6,7,8,1,4,5); // sample array sort($ar); // values are sorted, they may repeat $vals = array_count_values($ar); // values from $ar as indexes (now unique) $keys = array_keys($vals); // array with unique values and following indexes // third maximum value echo $keys[count($keys)-3]; ?> you should also test if the 'count($keys)-3' exists, for example: if isset().. note: small improvement, sorting $vals may be faster (smaller array), just rememer to sort keys not values: <?php $ar = array( 1,4,6,7,8,1,4,5); $vals = array_count_values($ar); // values as indexes, not in ascending order ksort($vals); // array sorting by keys $keys = array_keys($vals); echo $keys[count($keys)-3]; ?>
31st May 2017, 7:07 AM
Michal
Michal - avatar