分支循环,php 模板语法与 html 混编技巧
一.分支循环
<?php
//单分支
$age = 20;
if ($age >= 18) {
echo "用户已成年<br>";
}
//双分支
$age = 15;
if ($age >= 18) {
echo "用户已成年<br>";
} else {
echo "用户未成年<br>";
}
//三元表达式
$age = 25;
echo ($age >= 15) ? "用户已成年<br>" : "用户未成年<br>";
//多分支
$age = 35;
if ($age <= 18) {
echo "用户未成年<br>";
} else if ($age >= 18 && $age <= 30) {
echo "用户已成年,每天适当游戏时间<br>";
} else {
echo "用户已成年,合理安排游戏时间<br>";
};
//多分支的语法糖
$age = 28;
switch (true) {
case $age <= 18:
"用户未成年<br>";
break;
case $age >= 18 && $age <= 30:
echo "用户已成年,每天适当游戏时间<br>";
break;
default:
echo "用户已成年,合理安排游戏时间<br>";
break;
}
echo "<hr>";
//循环
$colors = ['red', 'green', 'blue'];
//初始化循环变量
$i = 0;
//设置循环条件
while ($i < count($colors)) {
echo $colors[$i] . "<br>";
//更新循环条件
$i = $i + 1;
}
//循环语法糖for
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "<br>";
}
echo "<hr>";
//中断或跳过某次循环
$colors = ['red', 'green', 'blue', 'red', 'green', 'blue'];
for ($i = 0; $i < count($colors); $i++) {
//只输出前五个
if ($i > 4) break;
//跳过第二个
if ($i === 1) continue;
echo $colors[$i] . "<br>";
}
二.php 模板语法与 html 混编技巧
<?php
$stus = [
['id' => 1, 'name' => '刘备', 'course' => 'js', 'score' => 83],
['id' => 2, 'name' => '关羽', 'course' => 'php', 'score' => 75],
['id' => 3, 'name' => '张飞', 'course' => 'js', 'score' => 52],
['id' => 4, 'name' => '孙权', 'course' => 'php', 'score' => 88],
['id' => 5, 'name' => '周瑜', 'course' => 'js', 'score' => 65],
['id' => 6, 'name' => '孔明', 'course' => 'php', 'score' => 53],
['id' => 7, 'name' => '赵云', 'course' => 'js', 'score' => 63],
['id' => 8, 'name' => '马超', 'course' => 'js', 'score' => 77],
['id' => 9, 'name' => '姜维', 'course' => 'php', 'score' => 93],
['id' => 10, 'name' => '黄忠', 'course' => 'js', 'score' => 81],
]
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>php模板语法与html混编技巧</title>
<style>
table {
border-collapse: collapse;
border: 1px solid black;
text-align: center;
width: 400px;
margin: 0 auto;
}
table th,
table td {
border: 1px solid black;
}
.js_course {
background-color: darkcyan;
}
.php_course {
background-color: burlywood;
}
.un_score {
background-color: red;
color: white;
}
</style>
</head>
<body>
<table>
<caption>学习成绩表</caption>
<thead>
<th>ID</th>
<th>姓名</th>
<th>课程</th>
<th>分数</th>
</thead>
<tbody>
<!-- 数组的遍历,foreach(数组 as 键名 =>值){...} -->
<?php foreach ($stus as $stu) : ?>
<tr>
<!-- <?php echo "123" ?> 简化为 <?= "123" ?> -->
<td><?= $stu["id"] ?></td>
<td><?= $stu["name"] ?></td>
<?php $course_type = ($stu["course"] === "js") ? "js_course" : "php_course" ?>
<td class=<?= $course_type ?>><?= $stu["course"] ?></td>
<?php $score_type = ($stu["score"] < 60) ? "un_score" : "" ?>
<td class=<?= $score_type ?>><?= $stu["score"] ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</body>
</html>