Home  >  Article  >  Backend Development  >  Code examples of PHP control structures if, switch, while, for, etc.

Code examples of PHP control structures if, switch, while, for, etc.

伊谢尔伦
伊谢尔伦Original
2017-06-23 09:40:421216browse

Control structure

1. IfConditional judgment statement

<meta http-equiv="content-type" content="text/html;charset=utf-8"/> 
<?php 
$a = 10; 
if ($a > 0) 
{ 
echo &#39;整数大于零&#39;; 
} 
echo &#39;<br/>&#39;; 
if ($a > 0) 
{ 
echo &#39;整数大于零&#39;; 
} 
else if($a < 0) 
{ 
echo &#39;整数小于零&#39;; 
} 
else 
{ 
echo &#39;整数等于零&#39;; 
} 
?>

2. Switch statement

<meta http-equiv="content-type" content="text/html;charset=utf-8"/> 
<?php 
$role = &#39;admin&#39;; 
switch ($role) 
{ 
case &#39;admin&#39; : 
echo &#39;管理员&#39;; 
break; 
case &#39;user&#39; : 
echo &#39;普通用户&#39;; 
break; 
case &#39;guest&#39; : 
echo &#39;游客&#39;; 
break; 
default : 
echo &#39;游客&#39;; 
break; 
} 
?>

3. While loopStatement

<?php 
$a = 10; 
while ( $a > 0 ) 
{ 
echo $a --; 
echo &#39;<br>&#39;; 
} 
?>


4. Do while loop statement

<?php 
$a = 10; 
do 
{ 
echo $a --; 
echo &#39;<br/>&#39;; 
} 
while ( $a > 0 ) 
?>

5. For loopStatement

<?php 
for($a = 0; $a < 10; $a++) 
{ 
echo $a; 
echo &#39;<br/>&#39;; 
} 
?>

6. Break statement

<meta http-equiv="content-type" content="text/html;charset=utf-8"/> 
<?php 
for($a = 0; $a < 10; $a++) 
{ 
echo $a; 
echo &#39;<br/>&#39;; 
if($a ==5) 
{ 
break;//终止循环,但执行循环后面的语句 
} 
} 
echo &#39;循环结束&#39;; 
?>

7. Exit statement

<?php 
for($a = 0; $a < 10; $a++) 
{ 
echo $a; 
echo &#39;<br/>&#39;; 
if($a ==5) 
{ 
exit;//直接退出,循环后面的语句不执行 
} 
} 
echo &#39;循环结束&#39;; 
?>

8. Continue statement

<?php 
for($a = 0; $a < 10; $a++) 
{ 
echo $a; 
echo &#39;<br/>&#39;; 
if($a ==5) 
{ 
continue;//结束本次循环,继续下次循环,循环后面的语句依然执行 
} 
} 
echo &#39;循环结束&#39;; 
?>


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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn