一.多分支结构与switch
- 单分支模板语法,用:开头,关键字结束
$amount = 1000;
$payment = $amount;
if ($amount >= 500) :
$payment = $amount * 0.9;
endif;
echo '实际支付:', $payment, '<br>';
- 双分支:if,else,endif
$amount = 400;
if ($amount >= 500) :
$payment = $amount * 0.9;
else :
$payment = $amount;
endif;
echo '实际支付:', $payment, '<br>';
- 多分支:if,elseif,else,endif
$amount = 3000;
if ($amount >= 1000 && $amount < 1500) :
$payment = $amount * 0.9;
elseif ($amount >= 1500 && $amount < 2000) :
$payment = $amount * 0.8;
elseif ($amount >= 2500) :
$payment = $amount * 0.7;
else :
$payment = $amount;
endif;
echo '实际支付:', $payment, '<br>';
- switch用来简化分支:switch,case,break,default
$amount = 500;
switch (true) {
case $amount >= 1000 && $amount < 1500:
$payment = $amount * 0.9;
break;
case $amount >= 1500 && $amount < 2000:
$payment = $amount * 0.8;
break;
case $amount >= 2500:
$payment = $amount * 0.7;
break;
default:
$payment = $amount;
}
echo '实际支付:', $payment, '<br>';
- 4.2.switch通常用在单值判断中
$discount = 0.8;
$amount = 3300;
switch ($discount):
case 0.7:
$payment = $amount * 0.7;
break;
case 0.8:
$payment = $amount * 0.8;
break;
case 0.9:
$payment = $amount * 0.9;
break;
default:
$payment = $amount;
endswitch;
echo '实际支付:', $payment, '<br>';
二.多种循环方式来遍历数组,while,for
1.while条件判断型循环,入口判断 - 条件是真就执行循环
$cities = ['北京', '深圳', '广州', '天津', '上海'];
while ($city = current($cities)) {
echo $city, '<br>';
next($cities);
}
怎么才能再次循环,必须指针复位
reset($cities);
while ($city = current($cities)) :
echo $city, '<br>';
next($cities);
endwhile;
2.判断型循环,出口判断型 do (…) while(条件)
- do - while 没有模板语法,此时第一个北京不见了
3.计数型循环:for(循环变量初始化,循环条件,更新循环条件){…}do {
echo $city, '<br>';
next($cities);
} while ($city = current($cities));
for ($i = 0; $i < count($cities); $i++) {
echo $cities[$i], '<br>';
}
echo '<hr>';
for ($i = 0; $i < count($cities); $i++) :
echo $cities[$i], '<br>';
endfor;
- 如果把第三个广州不要,广州值是2,输出拦截,后面的就终止不输出了
for ($i = 0; $i < count($cities); $i++) :
if ($i > 1) break;
echo $cities[$i], '<br>';
endfor;
- 选择性输出,跳过一些值广州
for ($i = 0; $i < count($cities); $i++) :
if ($i === 2) continue;
echo $cities[$i], '<br>';
endfor;