PHP- How can we get second highest number from a numeric array?

We can easily find second highest number from array.

Process of find the second largest number are in below simple steps

1. Create a numeric array like :

$array = array('200', '15','69','122','50','201','300');

2. Create two variable $first and $second and assign 0 value

3. Start for loop and add condition

for($i=0; $i < count($array); $i++)
{
 if($array[$i] > $first){
   $second = $first;
   $first = $array[$i];
 }
}

Complete code

 $array = array('200', '15','69','122','50','201','300');
 $first = 0;
 $second = 0;

 for($i=0; $i < count($array); $i++)
 {
    if($array[$i] > $first){
      $second = $first;
      $first = $array[$i];
    }
 }
 echo "Highest Number=".$first;
 echo "
"; echo "Second Highest Number=".$second;

No comments:

Post a Comment