簡體   English   中英

如何在PHP中從數組中找到最高,第二高的數字,最低的第二低的數字

[英]How to find highest ,second highest number, Lowest Second Lowest number from Array in PHP

php.ini 數組中最高、次高的數字以及最低或最小和次低的數字。

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

php中有幾種方法可以解決這個問題。

使用 PHP 內置方法系統

 $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";

使用 for 循環查找最高和第二大數字

$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.";

使用 for 循環查找最低和次低數字

    $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.";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM