Control structure
1. IfConditional judgment statement
<meta http-equiv="content-type" content="text/html;charset=utf-8"/> <?php $a = 10; if ($a > 0) { echo '整数大于零'; } echo '<br/>'; if ($a > 0) { echo '整数大于零'; } else if($a < 0) { echo '整数小于零'; } else { echo '整数等于零'; } ?>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/> <?php $role = 'admin'; switch ($role) { case 'admin' : echo '管理员'; break; case 'user' : echo '普通用户'; break; case 'guest' : echo '游客'; break; default : echo '游客'; break; } ?>
3. While loopStatement
<?php $a = 10; while ( $a > 0 ) { echo $a --; echo '<br>'; } ?>
4. Do while loop statement
<?php $a = 10; do { echo $a --; echo '<br/>'; } while ( $a > 0 ) ?>
5. For loopStatement
<?php for($a = 0; $a < 10; $a++) { echo $a; echo '<br/>'; } ?>
6. Break statement
<meta http-equiv="content-type" content="text/html;charset=utf-8"/> <?php for($a = 0; $a < 10; $a++) { echo $a; echo '<br/>'; if($a ==5) { break;//终止循环,但执行循环后面的语句 } } echo '循环结束'; ?>
7. Exit statement
<?php for($a = 0; $a < 10; $a++) { echo $a; echo '<br/>'; if($a ==5) { exit;//直接退出,循环后面的语句不执行 } } echo '循环结束'; ?>
8. Continue statement
<?php for($a = 0; $a < 10; $a++) { echo $a; echo '<br/>'; if($a ==5) { continue;//结束本次循环,继续下次循环,循环后面的语句依然执行 } } echo '循环结束'; ?>
The above is the detailed content of Code examples of PHP control structures if, switch, while, for, etc.. For more information, please follow other related articles on the PHP Chinese website!