
上QQ阅读APP看书,第一时间看更新
4.6 实战演练2——循环控制结构综合应用
下面以遍历已订房间门牌号为例介绍循环控制语句的应用技巧。
【例4.20】(实例文件:ch04\4.20.php)
<? php $bookedrooms = array('102', '202', '203', '303', '307'); // 定 义 数 组bookedrooms for ($i = 0; $i < 5; $i++){ //循环输出数组bookedrooms echo $bookedrooms[$i]."<br />"; } function checkbookedroom_while($bookedrooms){ //定义函数 $i = 0; while (isset($bookedrooms[$i])){ echo $i.":".$bookedrooms[$i]."<br />"; $i++; } } checkbookedroom_while($bookedrooms); $i = 0; do{ echo $i."-".$bookedrooms[$i]."<br />"; $i++; }while($i < 2); ?>
运行结果如图4-27所示。

图4-27 程序运行结果
其中,102~307由for循环实现。0:102~4:307由while循环实现。0:102和1:202由do…while循环实现。for循环和while循环都完全遍历了数组$bookedrooms,而do…while循环由于条件为while($i < 2),因此do后面的命令执行了两次。