Php 使用for循环从数组中获取最大数

Php 使用for循环从数组中获取最大数,php,max,Php,Max,我正在尝试从数组中获取最大的数字。但是没有得到它。我必须使用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]; } } ?> 如上所述,我必须对循环使用。它怎么了?那么: <?php $res = max(array(1,4

我正在尝试从
数组中获取最大的数字。但是没有得到它。我必须使用
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];
    }
}
?>

如上所述,我必须对
循环使用
。它怎么了?

那么:

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

这应该适合您:

<?php

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

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

    echo $res;

?>
在您的示例中,您只做错了两件事:

$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];
      }

}
$a=数组(1,44,5,6,68,9);
$res=$a[0];
对于($i=0;$i$a[$i]){
//^错误条件将其更改为<
$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];

}
$a=数组(1,44,5,6,68,9);
$res=0;
对于($count=0;$count
函数将执行您需要执行的操作:

$res = max($a);

更多详细信息。

您应该只使用三元运算符从$Isugest中删除= (情况)?(真实陈述):(虚假陈述)



$res=max($a)不为你工作?对不起,我用的是Loop对不起。我错过了那一点。对不起,我得用它loop@pawankumar更新了我的答案,但您的代码带有for循环,我向您展示了如何修复它,现在添加并举例说明它的外观。我只需要最高的单个数字(68)。@pawankumar
$res
等于68,就是那个数字!使用EchoOut for loop打印。echo$res;我得到了答案。再次感谢
$res = max($a);
<?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];
  }
}
?>
    <?php
      $items = array(1, 44, 5, 6, 68, 9);
      $max = 0;
      foreach($items as $item) {
        $max = ($max < $item)?$item:$max;
      }
      echo $max;
    ?>