通过for循环查找数组中的最大值和最小值

时间:2016-02-10 03:21:25

标签: php arrays for-loop

我想通过for循环找到最大值和最小值,但问题是当数组值从最大数字开始时(100,30,50,60),则输出是正确的第一个最大值,然后,最低价值。

否则输出第一个最小值,然后输出最大值。

任何想法?

    //Number serial.
    $number = array(10,15,20,100,25,30);

    for ($i=0; $i<count($number); $i++){
        //Find maximum number by max function.
        if ($number[$i] == max($number)){
            //Print maximum number.
            echo " The max number is $number[$i] <br>" ;
        }
        //Find minimum number by min function.
        elseif ($number[$i] == min($number)) {
            //Print minimum  number.
            echo " The min number is $number[$i] <br>";
        }
    }
//Output: 
//The min number is 10
//The max number is 100 

当数组值从最大数字开始时。

 //Number serial.
    $number = array(100,10,15,20,25,30);

    for ($i=0; $i<count($number); $i++){
        //Find maximum number by max function.
        if ($number[$i] == max($number)){
            //Print maximum number.
            echo " The max number is $number[$i] <br>" ;
        }
        //Find minimum number by min function.
        elseif ($number[$i] == min($number)) {
            //Print minimum  number.
            echo " The min number is $number[$i] <br>";
        }
    }
//Output:
//The max number is 100
//The min number is 10

3 个答案:

答案 0 :(得分:1)

实际上我认为你不需要开始使用for循环....你可以做这样简单的事情:

$number = array(15,20,100,10,25,30);
$max = max($number);
$min = min($number);
echo "min value is $min <br/>";
echo "max value is $max <br/>";

<强>更新

但是如果你想灵活地根据最小值和最大值的索引回应语句,那么你可以这样做:

$number = array(15,20,100,10,25,30);
$max = max($number);
$min = min($number);
$max_idx = array_search($max,$number);
$min_idx = array_search($min,$number);
if($max_idx < $min_idx){
  echo "max value is $max \n";
  echo "min value is $min \n";
}else{
  echo "min value is $min \n";
  echo "max value is $max \n";
}

这将是什么,它将获得最小值和最大值的索引,并且根据首先遇到的索引,它将首先打印该语句。

希望有所帮助

答案 1 :(得分:0)

使用以下代码。

$number = array(15,20,100,10,25,30);

for ($i=0; $i<count($number); $i++){
    //Find maximum number by max function.
    if ($number[$i] == max($number)){
        //Print maximum number.
        $max = $number[$i];
    }
    //Find minimum number by min function.
    elseif ($number[$i] == min($number)) {
    //Print minimum  number.
        $min = $number[$i];
    }
}

echo "min value is $min <br/>";
echo "max value is $max <br/>";

答案 2 :(得分:0)

<body bgcolor="lightgrey">
  <header>
    <h1>
      HEADING
    </h1>
  </header>
  <div id="wrapper">
    <div id="first">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>
    <div id="second">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    </div>

  </div>
  <footer>
    Footer text here
  </footer>
</body>

</html>