- 实例演示分支与循环, 不要抄源码 2. 实例演示流程控制之模板语法, 自己测试switch
1.分支
1.1分支
if($count > 0)
{
if($count == 1)
{
echo '1' . PHP_EOL;
}
elseif ($count == 2)
{
echo '2' . PHP_EOL;
}
else
{
echo '3' . PHP_EOL;
}
}
1.2语法糖
目标:判断大人小孩$age = 20;
$person = $age > 18 ? '大人' : '小孩';
echo $person . PHP_EOL;
2.循环
2.1switch循环
目标:判断是否及格
$m = 100;
switch ($m)
{
case $m<60:
echo '不及格';
break;
default:
echo '及格';
}
2.2 while循环
目标:输出0-9
$y = 10;
do{
echo $GLOBALS['y'];
static $count = 0;
echo $count . " ";
$count++;
}while($count < 10);
2.3 for循环
目标:屏幕上输出颜色
$color = ['red','blue','green'];
$list = '<ul style="border:1px solid red ;">';
for($i = 0;$i < count($color);$i++)
{
$list .= "<li>$color[$i]</li>";
}
$list .= '</ul>';
echo $list;
2.4 foreach循环
目标:遍历数组
$person = ['name' => 'yk','wight' => 60];
echo $person;
foreach ($person as $key => $value)
{
echo $key . ' ' . $value;
}
3.模板语法
3.1普通写法
<?php
$users = [
['1','吴昊','0',22],
['2','吴啊','1',23],
['3','爱昊','0',25],
]
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<style>
th,td{
border: 1px solid gray;
margin: 0;
}
</style>
<body>
<table style="border: 1px solid green;">
<caption>学生体检表</caption>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<?php
foreach ($users as $user)
{
echo '<tr>';
echo "<td>$user[0]</td>";
echo "<td>$user[1]</td>";
$sex = $user[2] ? '男' : '女';
echo '<td>'. $sex .'</td>';
echo "<td>$user[3]</td>";
echo '</tr>';
}
?>
</tbody>
</table>
</body>
</html>
3.2模板写法
<?php
$users = [
['1','吴昊','0',22],
['2','吴啊','1',23],
['3','爱昊','0',25],
]
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<style>
th,td{
border: 1px solid gray;
margin: 0;
}
</style>
<body>
<table style="border: 1px solid green;">
<caption>学生体检表</caption>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<?php
foreach ($users as $user):
?>
<tr>
<td><?=$user[0]?></td>
<td><?=$user[1]?></td>
<?php
$sex = $user[2] ? '男' : '女';
?>
<td><?=$sex?></td>
<td><?=$user[3]?></td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</body>
</html>