[英]Get Highest number from array using for loop
我試圖從array
獲得最高數字。 但沒有得到它。 我必須使用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
循環。 Wat有錯嗎?
這應該適合你:
<?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];
}
你應該只從 $i<=count 中刪除 = 所以它應該是
<?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];
}
}
?>
問題是你的循環在你的數組索引之后進行,並且條件顛倒了。
(健康)狀況) ? (真實陳述):(虛假陳述);
<?php
$items = array(1, 44, 5, 6, 68, 9);
$max = 0;
foreach($items as $item) {
$max = ($max < $item)?$item:$max;
}
echo $max;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.