Home php教程 php手册 PHP 循环控制语句几种方法详解

PHP 循环控制语句几种方法详解

Jun 13, 2016 am 09:51 AM
for php while generally use several kinds exist cycle control method yes Detailed explanation statement

在php中循环语句一般是使用while,for,foreach而控制语句就是if swicth这些了,下面我来给大家介绍一下php循环控制语句用法吧。

1、if..else循环有三种结构第一种是只有用到if条件,当作单纯的判断。

解释成"若发生了某事则怎样处理"。
语法如下:if(expr){statement}其中的expr为判断的条件,通常都是用逻辑运算符号当判断的条件。
而statement为符合条件的执行部分程序,若程序只有一行,可以省略大括号{}。
范例:本例省略大括号。

 代码如下 复制代码
if($state==1)
echo"哈哈";
?>

这里特别注意的是,判断是否相等是==而不是=,ASP程序员可能常犯这个错误,=是赋值。
范例:本例的执行部分有三行,不可省略大括号。

 代码如下 复制代码
if($state==1){
echo"哈哈;
echo"
";
}
?>

第两种是除了if之外,加上了else的条件,可解释成"若发生了某事则怎样处理,否则该如何解决"。
语法如下:

 代码如下 复制代码
if(expr){
statement1
}else{
statement2
}

范例:上面的例子来修改成更完整的处理。
其中的else由于只有一行执行的指令,因此不用加上大括号。

 代码如下 复制代码
if($state==1){
echo"哈哈";
echo"
";
}else{
echo"呵呵";
echo"
";
}
?>

第三种就是递归的if..else循环,通常用在多种决策判断时。
它将数个if..else拿来合并运用处理。
直接看下面的例子

 代码如下 复制代码
if($a>$b){
echo"a比b大";
}elseif($a==$b){
echo"a等于b";
}else{
echo"a比b小";
}
?>

上例只用二层的if..else循环,用来比较a和b两个变量。
实际要使用这种递归if..else循环时,请小心使用,因为太多层的循环容易使设计的逻辑出问题,或者少打了大括号等,都会造成程序出现莫名其妙的问题。
2、for循环就单纯只有一种,没有变化,它的语法如下
for(expr1;expr2;expr3){statement}
其中的expr1为条件的初始值。
expr2为判断的条件,通常都是用逻辑运算符号(logicaloperators)当判断的条件。
expr3为执行statement后要执行的部份,用来改变条件,供下次的循环判断,如加一..等等。
而statement为符合条件的执行部分程序,若程序只有一行,可以省略大括号{}。
下例是用for循环写的的例子。

 代码如下 复制代码
for($i=1;$i ){
echo"这是第".$i."次循环
";
}
?>

3、switch循环,通常处理复合式的条件判断,每个子条件,都是case指令部分。
在实作上若使用许多类似的if指令,可以将它综合成switch循环。语法如下

 代码如下 复制代码
switch(expr){
caseexpr1:
statement1;
break;
caseexpr2:
statement2;
break;
default:
statementN;
break;
}

其中的expr条件,通常为变量名称。
而case后的exprN,通常表示变量值。
冒号后则为符合该条件要执行的部分。
注意要用break跳离循环。

 代码如下 复制代码
switch(date("D")){
case"Mon":
echo"今天星期一";
break;
case"Tue":
echo"今天星期二";
break;
case"Wed":
echo"今天星期三";
break;
case"Thu":
echo"今天星期四";
break;
case"Fri":
echo"今天星期五";
break;
default:
echo"今天放假";
break;
}
?>

这里需要注意的是break;
别遗漏了,default,省略是可以的。
很明显的,上述的例子用if循环就很麻烦了。
当然在设计时,要将出现机率最大的条件放在最前面,最少出现的条件放在最后面,可以增加程序的执行效率。
上例由于每天出现的机率相同,所以不用注意条件的顺序。

php循环控制语句
1、While语句

 代码如下 复制代码
While循环是php中最简单的循环语句,他的语法格式是:
While (expression){
statement;
}

当表达式expression的值为真时,将执行statement语句,执行结束后,再返回到expression表达式继续进行判断。直到表达式的值为假时,才跳出循环。
实例:

 代码如下 复制代码
$num = 1;
$str = “10以内的偶数为:”;
while($num if($num % 2 == 0){
$str.=$num.”";
}
$num++;
}
echo $str;
?>

2、Do…While语句
While语句还有一种形式的表示,Do…While.语法为:
Do{
statement;
}While(expression);
两者的区别在于:Do…While语句要比While语句多循环一次。
当While表达式的值为假时,While循环直接跳出当前循环,而Do…While语句则是先执行一遍程序块,然后再对表达式进行判断。
3、For语句

 代码如下 复制代码
For循环是php中最复杂的循环结构,它的语法格式为:
For(expression1;expression2;expression3){
statement;
}

其中:expression1在第一次循环时无条件取一次值。
expression2在每次循环开始前求值,如果值为真,则执行statement;否则跳出循环,继续往下执行。expression3为每次循环后被执行。
实例:

 代码如下 复制代码
$num=1;
for($i=1;$i $num *=$i;
}
echo $num;
?>

4、Foreach语句
Foreach循环是php4.0引进来的,只能用于数组。在php5中,又增加了对对象的支持。该语句的语法格式为:
foreach(array_expression as $value)
statement;

Foreach(array_expression as $key => $value)
statement;
Foreach语句将遍历数组array_expression,每次循环时,将当前数组中的值赋给$value(或是将数组下表赋给$key、对应的数组值赋给$value),同时,数组指针向后移动,如此反复循环,直到遍历结束。当使用Foreach语句时,数组指针将自动被重置,所以不需要手动设置指针位置。实例

 代码如下 复制代码
$arr=array(“We”,”are”,”the”,”best”,”team”,”!”);
if(is_array($arr) == true){
foreach($arr as $key => $value){
echo $key.”=”.$value.”
”;
}
}else{
echo”该变量不是数组,不能使用foreach语句”;
}
?>
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles