php foreach 循环遍历求总分平均分
时间: 2024-10-09 08:05:39 浏览: 19
MongoDB数据库forEach循环遍历用法
在PHP中,`foreach`循环通常用于遍历数组,并可以用于计算总分和平均分。假设我们有一个包含学生成绩的关联数组,例如:
```php
$students = array(
'张三' => 90,
'李四' => 85,
'王五' => 95,
'赵六' => 80
);
```
首先,我们可以使用`foreach`循环遍历这个数组,累加所有学生的分数到 `$total_score` 变量,同时记录学生数量到 `$count` 变量:
```php
$total_score = 0;
$count = count($students);
foreach ($students as $name => $score) {
$total_score += $score;
}
```
接着,计算平均分,只需将 `total_score` 除以 `$count`:
```php
$average_score = $total_score / $count;
```
完整代码示例:
```php
$students = array(
'张三' => 90,
'李四' => 85,
'王五' => 95,
'赵六' => 80
);
$total_score = 0;
$count = count($students);
foreach ($students as $name => $score) {
$total_score += $score;
}
$average_score = $total_score / $count;
echo "总分:$total_score<br>";
echo "平均分:$average_score";
```
阅读全文