尋找計算$ data數組的平均值。我需要首先找到數組中值的總和。這是我擁有的,但似乎並不奏效。PHP中數組的總和
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
return $sum;
}
$count = count($data);
$average = $sum/$count;
echo "Average is $average <br />";
尋找計算$ data數組的平均值。我需要首先找到數組中值的總和。這是我擁有的,但似乎並不奏效。PHP中數組的總和
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
return $sum;
}
$count = count($data);
$average = $sum/$count;
echo "Average is $average <br />";
試試這個:
$total = array_sum($data);
$average = $total/count($data);
或者,如果你喜歡的俏皮話:
$average = array_sum($data)/count($data);
刪除return
$sum = 0;
foreach($data as $value) {
$sum = $sum+$value;
}
$count = count($data);
$average = $sum/$count;
echo "Average is $average <br />";
它的失敗的原因是你不應該有return
聲明。 return
僅用於從函數返回。
也就是說,您可以使用array_sum()
代替。