我想从数组中获得最高数字.但没有得到它.我必须使用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];
}
}
?>
我必须使用for循环,如上所述.扫管笏是错的吗?
解决方法:
这应该适合你:
<?PHP
$a = array(1, 44, 5, 6, 68, 9);
$res = 0;
foreach($a as $v) {
if($res < $v)
$res = $v;
}
echo $res;
?>
输出:
68
在你的例子中,你只做了两件事:
$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];
}
}
编辑:
使用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];
}