批改状态:未批改
老师批语:
知识点:
for:循环执行代码块指定的次数。
while:循环在指定条件为 true 时执行代码块。
foreach:循环只适用于数组,并用于遍历数组中的每个键/值对。
今天我们来用for、while和foreach这3个循环函数来做一个简单成绩表。
效果图:

<?php
$name=['王小明','玛丽','邓雪冰','李军','第五杰','芳华','张敏','蔡丽丽'];
$grade=[60,50,88,77,45,72,100,99];
$table = '<table border="1" cellspacing="0" cellpadding="5" width="500" style="text-align:center">';
$table .= '<caption>会员成绩表for</caption>';
//for循环
for($i=0;$i<count($name);$i++){
$table .='<tr>';
$table .='<td>'.$name[$i].'</td>';
$table .='<td>'.$grade[$i].'</td>';
$table .= '</tr>';
}
$table .= '</table>';
echo $table;
$table='';
$table = '<table border="1" cellspacing="0" cellpadding="5" width="500" style="text-align:center">';
$table .= '<caption>会员成绩表while</caption>';
$i=0;//在while前得先定义$i的值。
//while循环
while ($i<count($name)) {
$table .='<tr>';
$table .='<td>'.$name[$i].'</td>';
$table .='<td>'.$grade[$i].'</td>';
$table .='</tr>';
$i++;//在while循环后必须要加个自增
}
$table .= '</table>';
echo $table;
$table='';
$table = '<table border="1" cellspacing="0" cellpadding="5" width="500" style="text-align:center">';
$table .= '<caption>会员成绩表foreach</caption>';
//foreach循环
foreach ($name as $key => $value) {
$table .='<tr>';
$table .='<td>'.$value.'</td>';
$table .='<td>'.$grade[$key].'</td>';//这里输出另一个数组,用本次循环数组的索引来或者这另一个数组
$table .='</tr>';
}
$table .= '</table>';
echo $table;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号