Blogger Information
Blog 48
fans 3
comment 1
visits 36989
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php循环函数:for、while、foreach——2018年4月17日
JackBlog
Original
781 people have browsed it

知识点:

for:循环执行代码块指定的次数。

while:循环在指定条件为 true 时执行代码块。

foreach:循环只适用于数组,并用于遍历数组中的每个键/值对。 

今天我们来用for、while和foreach这3个循环函数来做一个简单成绩表。

效果图:

QQ截图20180418111410.png

实例

<?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;

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!