简体   繁体   中英

Get Highest number from array using for loop

I am trying to get highest number from array . But not getting it. I have to get highest number from the array using for loop.

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

I have to use for loop as i explained above. Wat is wrong with it?

This should work for you:

<?php

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

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

    echo $res;

?>

Output:

68

In your example you just did 2 things wrong:

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

}

EDIT:

With a for loop:

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

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

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

}

What about:

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

( docs )

you should only remove the = from $i<=count so it should be

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

the problem is that your loop goes after your arrays index and the condition is reversed.

The max() function will do what you need to do :

$res = max($a);

More details here .

Suggest using Ternary Operator

(Condition) ? (True Statement) : (False Statement);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM