PHP循环结构与流程控制
程序最强大的地方在于可以重复执行任务——这就是循环的作用。这篇文章会介绍PHP中的各种循环语句,让你的程序能够自动完成重复性的工作。
一、为什么需要循环?
假设要打印1到100的数字,不用循环的话:
<?phpecho"第1个数字\n";echo"第2个数字\n";echo"第3个数字\n";// ... 还要写97行?>
用循环,一行代码就搞定了:
<?phpfor ($i = 1; $i <= 100; $i++) {echo"第{$i}个数字\n";}?>
这就是循环的力量。
二、for循环
for循环是最常用的循环,适合已知循环次数的场景:
<?php// 语法:for (初始值; 条件; 步进) { 循环体 }// 打印1到10echo"打印1到10:\n";for ($i = 1; $i <= 10; $i++) {echo$i . " ";}echo"\n";// 计算1到100的累加和echo"\n计算1到100的累加和:\n";$sum = 0; // 初始化累加器for ($i = 1; $i <= 100; $i++) {$sum += $i; // $sum = $sum + $i}echo"1 + 2 + 3 + ... + 100 = " . $sum . "\n"; // 输出5050// 打印九九乘法表echo"\n九九乘法表:\n";for ($i = 1; $i <= 9; $i++) {for ($j = 1; $j <= $i; $j++) {echo"{$i}×{$j}=" . ($i * $j) . "\t"; }echo"\n";}?>
代码讲解:
for ($i = 0; $i < 10; $i++)是最常见的写法,遍历0到9
输出结果(部分):
打印1到10:1 2 3 4 5 6 7 8 9 10 计算1到100的累加和:1 + 2 + 3 + ... + 100 = 5050九九乘法表:1×1=1 2×1=2 2×2=4 3×1=3 3×2=6 3×3=9 ...
三、while循环
while循环适合不知道具体循环次数的场景:
<?php// 猜数字游戏$secret = 37; // 秘密数字$guess = 0; // 猜测值$attempts = 0; // 尝试次数echo"猜数字游戏(1-100):\n";while ($guess != $secret) { // 条件为真时继续循环$attempts++;// 模拟猜测(实际中这里会是用户输入)$guess = rand(1, 100);if ($guess < $secret) {echo"第{$attempts}次:{$guess} 太小了,再大一点!\n"; } elseif ($guess > $secret) {echo"第{$attempts}次:{$guess} 太大了,再小一点!\n"; }// 防止无限循环(如果随机猜到的话)if ($attempts >= 100) {echo"尝试次数太多,游戏结束!\n";break; // 强行退出循环 }}if ($guess == $secret) {echo"\n恭喜!答案就是{$secret},你用了{$attempts}次猜对!\n";}?>
代码讲解:
四、do-while循环
do-while至少会执行一次循环体:
<?php// 菜单系统$choice = "";do {echo"\n===== 菜单 =====\n";echo"1. 查看余额\n";echo"2. 存款\n";echo"3. 取款\n";echo"4. 退出\n";echo"请选择(1-4):";// 模拟用户选择(实际中是用户输入)$choice = rand(1, 4);echo$choice . "\n";switch ($choice) {case1:echo"您的余额:¥10000.00\n";break;case2:echo"存款成功!\n";break;case3:echo"取款成功!\n";break;case4:echo"感谢使用,再见!\n";break; }} while ($choice != 4); // 注意这里有分号?>
代码讲解:
do-while和while的区别:do-while先执行一次,再判断条件- 所以即使条件一开始就不满足,循环体也会执行至少一次
五、foreach循环
foreach是专门用来遍历数组的:
<?php// 遍历索引数组$fruits = ["苹果", "香蕉", "橙子", "葡萄", "西瓜"];echo"水果列表:\n";foreach ($fruitsas$index => $fruit) {echo ($index + 1) . ". " . $fruit . "\n";}// 遍历关联数组echo"\n学生信息:\n";$student = ["name" => "李明","age" => 20,"major" => "计算机科学","grade" => "大三"];foreach ($studentas$key => $value) {// 根据键名做不同处理$label = match($key) {"name" => "姓名","age" => "年龄","major" => "专业","grade" => "年级",default => $key };echo$label . ":" . $value . "\n";}?>
代码讲解:
foreach ($array as $item):遍历数组,只获取值foreach ($array as $key => $item):遍历数组,同时获取键和值as $index => $fruit中,$index是数字索引,$fruit是值
六、流程控制:break和continue
<?php// 找出1-100中第一个能被7整除的数字echo"找出1-100中第一个能被7整除的数字:\n";for ($i = 1; $i <= 100; $i++) {if ($i % 7 == 0) { // % 是取余运算符echo"找到了:是{$i}\n";break; // 找到后立即退出循环,不再继续 }}// 计算1-100中偶数的和,但跳过10到20之间的数echo"\n计算1-100中偶数的和(跳过10-20):\n";$sum = 0;$count = 0;for ($i = 1; $i <= 100; $i++) {if ($i >= 10 && $i <= 20) {continue; // 跳过这次循环,继续下一次 }if ($i % 2 == 0) { // 偶数$sum += $i;$count++; }}echo"偶数个数:{$count}个\n";echo"偶数总和:{$sum}\n";?>
代码讲解:
continue:跳过本次循环的剩余代码,继续下一次循环
七、实战:筛选数组数据
<?php// 成绩列表$scores = [85, 92, 78, 96, 67, 88, 73, 95, 82, 59, 100, 45];echo"原始成绩:" . implode(", ", $scores) . "\n";// 找出不及格的成绩echo"\n不及格(<60分):\n";$failed = [];foreach ($scoresas$score) {if ($score < 60) {$failed[] = $score; // [] 是 array_push() 的简写 }}echoimplode(", ", $failed) . "\n";// 计算平均分$average = array_sum($scores) / count($scores);echo"\n平均分:" . round($average, 2) . "分\n"; // round() 四舍五入// 统计各等级人数echo"\n成绩等级分布:\n";$grade_counts = ["A(90+)" => 0, "B(80-89)" => 0, "C(70-79)" => 0, "D(60-69)" => 0, "F(<60)" => 0];foreach ($scoresas$score) {if ($score >= 90) {$grade_counts["A(90+)"]++; } elseif ($score >= 80) {$grade_counts["B(80-89)"]++; } elseif ($score >= 70) {$grade_counts["C(70-79)"]++; } elseif ($score >= 60) {$grade_counts["D(60-69)"]++; } else {$grade_counts["F(<60)"]++; }}foreach ($grade_countsas$grade => $count) {echo"{$grade}:{$count}人\n";}?>
代码讲解:
implode(", ", $array)把数组元素用分隔符连接成字符串$array[] = $value是往数组末尾添加元素的简写方式
八、写在最后
循环是编程中最强大的工具之一。记住:for适合已知次数,while适合条件驱动,foreach专门处理数组。下一篇我们会学习函数,那是更高层次的代码组织方式。