find second highest value in array using php

1) First step is to sort the array in desc.
2) create two variable  like $fh as first highest and $sh as second highest.
3) loop the array in foreach ,we will check the if condition to first val is greater then $fh variable ,where first iteration first highest value will be assigned to $fh value.
4) second  else if condition will be same ,but here variable will be $sh and another condition in is check duplicate value of highest in the array.

$arr = [55,40,50,76,76,40,30,20,60,89];
rsort($arr);
$fh=0;
$sh=0;
foreach($arr as $val){
    if($val > $fh){
        $fh = $val;
    } elseif(($val>$sh) && ($val != $fh)){
        $sh = $val;
    }
 
}
echo $sh;

Comments

Popular posts from this blog

create pdf by using javascript

yii framework simple shopping cart tutorial for beginners

yii2 arrayhelper::map vs array_map