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

伊谢尔伦
Release: 2023-03-11 07:42:01
Original
1266 people have browsed it

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;; 
} 
?>
Copy after login

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; 
} 
?>
Copy after login

3. While loopStatement

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


4. Do while loop statement

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

5. For loopStatement

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

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;; 
?>
Copy after login

7. Exit statement

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

8. Continue statement

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


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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!