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?
potashin
44.7k11 gold badges92 silver badges113 bronze badges
asked Jan 4, 2015 at 0:45
5 Answers 5
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];
}
answered Jan 4, 2015 at 0:49
-
Sorry i have to use for looppawan kumar– pawan kumar01/04/2015 01:19:54Commented Jan 4, 2015 at 1:19
-
@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 likeRizier123– Rizier12301/04/2015 01:23:02Commented Jan 4, 2015 at 1:23
-
I need only highest single number (68).pawan kumar– pawan kumar01/04/2015 01:24:53Commented Jan 4, 2015 at 1:24
-
@pawankumar
$res
is equal 68 it is that number! print it with echoRizier123– Rizier12301/04/2015 01:25:28Commented Jan 4, 2015 at 1:25 -
1outside for loop . echo $res; i got answer. Thanks againpawan kumar– pawan kumar01/04/2015 01:28:16Commented Jan 4, 2015 at 1:28
answered Jan 4, 2015 at 0:48
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.
answered Jan 4, 2015 at 0:55
potashin
44.7k11 gold badges92 silver badges113 bronze badges
-
sorry i am using for looppawan kumar– pawan kumar01/04/2015 00:54:53Commented Jan 4, 2015 at 0:54
-
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;
?>
lang-php
$res = max($a);
not working for you?