3

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?

1
  • 2
    $res = max($a); not working for you? Commented Jan 4, 2015 at 0:47

5 Answers 5

4

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry i have to use for loop
@pawankumar updated my answer, but your code is with a for loop and i showed you where to fix it, added now and example how it should look like
I need only highest single number (68).
@pawankumar $res is equal 68 it is that number! print it with echo
outside for loop . echo $res; i got answer. Thanks again
3

What about:

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

(docs)

Comments

1

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.

Comments

0

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

$res = max($a);

More details here.

2 Comments

sorry i am using for loop
Sorry. I missed that bit.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.