PHP中for循环语句的几种变型_PHP
for 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是:
for (expr1; expr2; expr3)
statement
第一个表达式(expr1)在循环开始前无条件求值一次。
expr2 在每次循环开始前求值。如果值为 TRUE,则继续循环,执行嵌套的循环语句。如果值为 FALSE,则终止循环。
expr3 在每次循环之后被求值(执行)。
每个表达式都可以为空。expr2 为空意味着将无限循环下去(和 C 一样,PHP 认为其值为 TRUE)。这可能不像想象中那样没有用,因为经常会希望用 break 语句来结束循环而不是用 for 的表达式真值判断。
考虑以下的例子,它们都显示数字 1 到 10:
/* example 1 */
for ($i = 1; $i echo $i;
}
/* example 2 */
for ($i = 1; ; $i ) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (;;) {
if ($i > 10) {
break;
}
echo $i;
$i ;
}
/* example 4 */
for ($i = 1; $i ?>
当然,第一个例子看上去最正常(或者第四个),但用户可能会发现在 for 循环中用空的表达式在很多场合下会很方便。
PHP 也支持用冒号的 for 循环的替代语法。
for (expr1; expr2; expr3):
statement;
...
endfor;
for语句可以说是PHP(同时也是多种语言)的循环控制部份最基本的一个语句了,for语句的执行规律和基础用法在这里就不多说。PHP手册中对它的语法定义如下:
for (expr1; expr2; expr3)
statement
下面说说for语句几种有用的变型。
1、无限循环
首先是人尽皆知的无限循环(亦可称“死循环”)。由于空表达式null在语法上是有效的,所以我们可以把for语句的三个表达式留空,这样就会产生不断执行for嵌套语句的效果。
for (;;) {
//放置需要不断执行的语句
}
?>
虽然有一些任务会使用到无限循环,但是大多数程序任务,特别是PHP所能涉及的领域,在使用无限循环时都会添加一些终止循环的条件。
for (;;) {
//如果是公元2199年,则跳出循环
if (date('Y') == '2199') {
break;
}
}
?>
2、使用空表达式
接下来就是说说在初始化语句expr1中使用null语法,留空expr1最常见的作用就是完成更为复杂的初始化工作。
if (isset($i)) {
unset($i);
if ((int) date('') $i = 0;
} else {
$i = 1;
}
} else {
$i =3;
}
for (;$i echo $i;
}
?>
同样道理,迭代表达式expr3也可能留空,也可以利用这点编写更为复杂的迭代式,比如说根据不同的条件调用不同的迭代式。
而for语句中的条件语句expr2留空则是上面所说的无限循环,当然也可以添加一些更为复杂的条件去判断什么时候跳出循环,在此不在重复。
3、多重循环
使用多重循环来控制多个变量也是在for语句中使经常被忽略的一个特性。如下面的例子,在一般的任务中用到的一般会是双重循环,三重以上的循环一般意义不大。
for ($i = 0, $j = 10;$i echo "$i $j = 10\r\n";
}
?>
以上代码将输出:
0 10 = 10
1 9 = 10
2 8 = 10
3 7 = 10
4 6 = 10
5 5 = 10
6 4 = 10
7 3 = 10
8 2 = 10
9 1 = 10
10 0 = 10
4、更为复杂的表达式
如果把for语句的三个表达式写得复杂一些,则可以用于优化算法。甚至可以使用没有循环体的for语句来完成一些任务。比如计算累加或阶乘:
//计算1-5的累加结果,斌值到$j
for ($i = 1,$j = 0; $i echo $j;
//计算1-5的阶乘结果,斌值到$j
for ($i = 1,$j = 1; $i echo $j;
?>

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

With the rapid development of network technology, our lives have also been greatly facilitated, one of which is the ability to download and share various resources through the network. In the process of downloading resources, magnet links have become a very common and convenient download method. So, how to use Thunder magnet links? Below, I will give you a detailed introduction. Xunlei is a very popular download tool that supports a variety of download methods, including magnet links. A magnet link can be understood as a download address through which we can obtain relevant information about resources.
