Today we are going to learn how to find the second largest number from an array using php. This question is often asked by interviewers. So, let’s write php code to get second largest number from given array.
For example:
Given $array=array(2,4,3,11,2,86,34,1);
PHP Code to get the second largest number from given array
<?php
function findSecondMax(array $arr) {
$max = PHP_INT_MIN;
$secondMax = PHP_INT_MIN;
foreach($arr as $number) {
if($number > $max) {
$secondMax = $max;
$max = $number;
}
if($number > $secondMax && $number < $max) {
$secondMax = $number;
}
}
return $secondMax;
}
$array=array(2,4,3,11,2,86,34,1);
echo findSecondMax($array); //output will be 34
?>
What we did here?
We used PHP_INT_MIN which returns the smallest possible number. We took two variables $max and $secondMax and in the loop we checked if compare each $numbers with $max. If the $number is grater than $max then the biggest digit would be the $number and the $max would be the $secondMax. This is the way you write PHP code to get the second largest number from an array.
That’s it.