php switch
- 1. switch
- 2. for循环
- 3. foreach
- 4. while、do...while
1. switch
<?php
$height = 190;
switch ($height) {
case 160:
echo '太矮了';
break; //跳出本次循环
case 170:
echo '还行吧';
break; //跳出本次循环
case 180:
echo '帅哥';
break; //跳出本次循环
default:
echo '迷';
}
2. for循环
<?php
for ($i = 0; $i < 10; $i++) {
echo '花了' . $i . '元';
}
3. foreach
<?php
$daShuaiGe = array('a', 'b', 1, 2, true);
foreach ($daShuaiGe as $key => $value)
{
var_dump($key . ' ' . $value);
}
4. while、do…while
while 循环会在每次循环开始前检查条件是否为真。如果条件为真,则执行循环体内的代码。如果条件为假,则跳出循环。
$total = 0;
$i = 1;
while ($i <= 5) {
$total += $i;
$i++;
}
echo $total; // 输出 15
do…while 循环会先执行一次循环体,然后检查条件是否为真。如果条件为真,则继续执行循环体,直到条件为假为止。
do…while 循环保证循环体至少执行一次,即使条件一开始就为假。例如,以下代码会输出"Hello" 5次:
$count = 5;
do {
echo "Hello\n";
$count--;
} while ($count > 0);