簡體   English   中英

使用 for 循環從數組中獲取最大數字

[英]Get Highest number from array using for loop

我試圖從array獲得最高數字。 但沒有得到它。 我必須使用for循環從數組中獲取最高數字。

<?php
$a =array(1, 44, 5, 6, 68, 9);
$res=$a[0];
for($i=0; $i<=count($a); $i++){
    if($res>$a[$i]){
        $res=$a[$i];
    }
}
?>

正如我上面解釋的那樣,我必須使用for循環。 Wat有錯嗎?

這應該適合你:

<?php

    $a = array(1, 44, 5, 6, 68, 9);
    $res = 0;

    foreach($a as $v) {
        if($res < $v)
            $res = $v;
    }

    echo $res;

?>

輸出:

68

在您的示例中,您只是做錯了兩件事:

$a = array(1, 44, 5, 6, 68, 9);
$res = $a[0];

for($i = 0; $i <= count($a); $i++) {
              //^ equal is too much gives you an offset!

      if($res > $a[$i]){
            //^ Wrong condition change it to < 
          $res=$a[$i];
      }

}

編輯:

使用 for 循環:

$a = array(1, 44, 5, 6, 68, 9);
$res = 0;

for($count = 0; $count < count($a); $count++) {

    if($res < $a[$count])
        $res = $a[$count];

}

關於什么:

<?php
    $res = max(array(1,44,5,6,68,9));

文檔

你應該只從 $i<=count 中刪除 = 所以它應該是

<?php $a =array(1,44,5,6,68,9);
$res=$a[0];
for($i=0;$i<count($a);$i++){
  if($res<$a[$i]){
   $res=$a[$i];
  }
}
?>

問題是你的循環在你的數組索引之后進行,並且條件顛倒了。

max()函數會做你需要做的事情:

$res = max($a);

更多細節在這里

建議使用三元運算符

(健康)狀況) ? (真實陳述):(虛假陳述);

    <?php
      $items = array(1, 44, 5, 6, 68, 9);
      $max = 0;
      foreach($items as $item) {
        $max = ($max < $item)?$item:$max;
      }
      echo $max;
    ?>

暫無
暫無

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

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