php中循环之for()、while()、foreach()用法
本文章介绍最基本的循环语句的用法,在php中包括了for()、while()、foreach() do while 这几种最基本的语句。
while循环
while循环是PHP中最简单的循环,其基本格式为:
代码如下 | 复制代码 |
while (expr){ statement } //或者 while (expr): statement endwhile; |
该语法表示,只要expr表达式为TRUE,那么就一直执行statement直到expr为FALSE为止,statement表示要执行的动作或逻辑。
例子:
代码如下 | 复制代码 |
$i = 1; while ($i echo $i; $i++; } ?> |
该例子循环输出1到10。
do-while循环
do-while循环和while循环非常相似,其区别只是在于do-while保证必须执行一次,而while在表达式不成立时则可能不做任何操作。
do-while 循环只有一种语法:
代码如下 | 复制代码 |
do { statement }while (expr) |
例子:
代码如下 | 复制代码 |
$i = 1; do { echo $i; $i++; } while ($i ?> |
该例子也是输出1到10
for循环
for循环是PHP中更为复杂的循环,其语法如下:
代码如下 | 复制代码 |
for (expr1; expr2; expr3){ statement } |
下面的例子依然输出1到10:
代码如下 | 复制代码 |
for ($i = 1; $i
echo $i; } ?> |
语法解读
第一个表达式(expr1)在循环开始前无条件求值一次
expr2 在每次循环开始前求值,如果值为 TRUE,则继续循环,执行嵌套的循环语句;如果值为 FALSE,则终止循环。
expr3 在每次循环之后被求值(执行)
每个表达式都可以为空。如果expr2 为空意则将无限循环下去,但可以通过break来结束循环:
代码如下 | 复制代码 |
for ($i = 1; ; $i++) { if ($i > 10) { break; } echo $i; } ?> |
提示
在使用循环语句的时候,我们通常要注意不要无限循环而造成程序“僵死”,另外还要注意循环条件(循环判断表达式),以确保循环结果正确。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools