Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Highest number from array using for loop

Tags:

php

max

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?

like image 741
pawan kumar Avatar asked Apr 26 '26 23:04

pawan kumar


1 Answers

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

}
like image 185
Rizier123 Avatar answered Apr 28 '26 16:04

Rizier123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!