How to Find largest number in array Using PHP

This sample program is very helpful for the School / College kids who are willing to become a PHP developer. And in the interviews these kind of questions asked many times. So it is always good to be prepared.

Example

<?php 
$array = array(5,7,81,0,12);
 
$max1 =0 ;
$max2 = 0;
 
for($i=0; $i<count($array); $i++)
{
    if($array[$i] > $max1)
    {
      $max2 = $max1;
      $max1 = $array[$i];
    }
    else if($array[$i] > $max2)
    {
      $max2 = $array[$i];
    }
}
echo "Maximum value = ".$max1;
echo "<br />"; 
echo "Second maximum Value =".$max2;
?> 

Leave a Reply

Your email address will not be published. Required fields are marked *