-2

Highest, second highest number and lowest or smallest and second lowest number from an array in php.

$array = array('2','1','200','15','300','500','69','422','399','201','299');

lincolndu
  • 93
  • 1
  • 8
  • 2
    Welcome to SO. Please read [What topics can I ask about](http://stackoverflow.com/help/on-topic) and [How to ask a good question](http://stackoverflow.com/help/how-to-ask) And [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) And how to create a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve) SO is **not a free Coding or Code Conversion or Debugging or Tutorial or Library Finding service** ___Here at SO we fix your attempts, we do not write code for you___ – RiggsFolly Jan 12 '17 at 23:06

1 Answers1

0

There are several ways in php to solve this problem.

Use PHP Built in method system

 $array = array('2','1','200','15','300','500','69','422','399','201','299');
//First order the array 
sort($array);
 $lowest = $array[0];
 $secondLowest = $array[1];
 $highest = $array[count($array)-1];
 $SecondHighest = $array[count($array)-2];

echo "Lowest number is $lowest, Second lowest number is $secondLowest and Highest number is $highest, Seoncd highest is $SecondHighest";

Find Highest and Second highest number with for loop

$array = array('2','1','200','15','300','500','69','422','399','201','299');
$secondHighest=$highest=0;
for ($i=0; $i < count($array); $i++) { 

    if ($array[$i] > $highest ) {
        $secondHighest=$highest;
        $highest=$array[$i];
    }elseif ( $array[$i] > $secondHighest ) {
        $secondHighest= $array[$i];
    }
}

echo "Highest number is $highest and Second highest number is $secondHighest.";

Find Lowest and Second Lowest number with for loop

    $array = array('2','1','200','15','300','500','69','422','399','201','299');

$lowest=$array[0];
$gotLowest=0;
$smallArray=[];
$secondLowest=0;
$lowestnext=0;

for ($i=0; $i < count($array); $i++) { 
    // find lowest value and run only first time
    if($gotLowest == 0 ){
        for ($k=0; $k < count($array) ; $k++) { 
            if ( intval($array[$k]) < $lowest ) {
                $lowest= $array[$k]; //lowest value
            }           
        }
        $gotLowest=1; // change value so that run this condition only one time
    }

    if ( $lowestnext ==0 && intval($array[$i]) > $lowest) {
         $lowestnext=$array[$i];
    }
    // find second smaller value from array
    if ( $array[$i] > $lowest && $array[$i] <= $lowestnext ) {
        $smallArray[] = $array[$i];
        for ($j=0; $j < count($smallArray); $j++) { 
            if ( $smallArray[$j] < $secondLowest ) {
                $secondLowest=$smallArray[$j];
            }
        }
        $secondLowest=$smallArray[0];
    }
}


echo "Lowest number is $lowest and Second Lowest number is $secondLowest.";
lincolndu
  • 93
  • 1
  • 8