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 :

1
$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

1
2
3
4
5
6
7
for($i=0; $i < count($array); $i++)
{
 if($array[$i] > $first){
   $second = $first;
   $first = $array[$i];
 }
}

Complete code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$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 "<br>";
echo "Second Highest Number=".$second;

No comments:

Post a Comment