Home Backend Development PHP Tutorial The usage and difference between for loop and foreach loop in PHP

The usage and difference between for loop and foreach loop in PHP

Mar 01, 2018 am 10:52 AM
foreach php usage

本篇文章我们来讲讲PHP中的for循环foreach循环的用法和区别,相信有很多同学可能并不是怎么清楚for循环和foreach循环的区别到底在哪里,我们今天就来详细的讲一下!

for 循环是 PHP 中最复杂的循环结构。

它的行为和 C 语言的相似。

for 循环的语法是:

for (expr1; expr2; expr3) statement
第一个表达式(expr1)在循环开始前无条件求值一次。
expr2 在每次循环开始前求值。如果值为 TRUE,则继续循环,执行嵌套的循环语句。如果值为 FALSE,则终止循环。
expr3 在每次循环之后被求值(执行)。
每个表达式都可以为空。expr2 为空意味着将无限循环下去(和 C 一样,PHP 认为其值为 TRUE)。这可能不想你想象中那样没有用,因为你经常会希望用 break 语句来结束循环而不是用 for 的表达式真值判断。
考虑以下的例子。它们都显示数字 1 到 10:

for ($i = 1; $i <= 10; $i++) {
    print $i;
}
for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    print $i;
}
$i = 1;
for (; ;) {
    if ($i > 10) {
        break;
    }
    print $i;
    $i++;
}
for ($i = 1; $i <= 10; print $i, $i++) ;
Copy after login

当然,第一个例子看上去最正常(或者第四个),但你可能会发现在 for 循环中用空的表达式在很多场合下会很方便。

PHP 也支持用冒号的 for 循环的替代语法。
for (expr1; expr2; expr3): statement; ...; endfor;
其它语言具有 foreach 语句来遍历数组或散列表,PHP 也行(见 foreach)。在 PHP 3 中,可以结合 list()和 each() 函数用 while 循环来达到同样效果。例子见这些函数的文档。

foreach
PHP 4(不是 PHP 3)包括了 foreach 结构,和 Perl 以及其他语言很像。这只是一种遍历数组简便方法。foreach 仅能用于数组,当试图将其用于其它数据类型或者一个未初始化的变量时会产生错误。有两种语法,第二种比较次要但却是第一种的有用的扩展。

foreach (array_expression_r_r as $value) statement foreach (array_expression_r_r as $key => $value) statement
第一种格式遍历给定的 array_expression_r_r 数组。每次循环中,当前单元的值被赋给 $value 并且数组内部的指针向前移一步(因此下一次循环中将会得到下一个单元)。
第二种格式做同样的事,只除了当前单元的键值也会在每次循环中被赋给变量 $key。
注: 当 foreach 开始执行时,数组内部的指针会自动指向第一个单元。这意味着不需要在 foreach 循环之前调用 reset()。
注: 此外注意 foreach 所操作的是指定数组的一个拷贝,而不是该数组本身。因此即使有 each() 的构造,原数组指针也没有变,数组单元的值也不受影响。
注: foreach 不支持用“@”来禁止错误信息的能力。
你可能注意到了以下的代码功能完全相同:

$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br>\n";
}
foreach ($arr as $value) {
    echo "Value: $value<br>\n";
}
Copy after login

以下代码功能也完全相同:

reset($arr);
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br>\n";
}
foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br>\n";
}
Copy after login

示范用法的更多例子:

$a = array(1, 2, 3, 17);
foreach ($a as $v) {
    print "Current value of \$a: $v.\n";
}
$a = array(1, 2, 3, 17);
$i = 0;
foreach ($a as $v) {
    print "\$a[$i] => $v.\n";
    $i++;
}
$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);
foreach ($a as $k => $v) {
    print "\$a[$k] => $v.\n";
}
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        print "$v2\n";
    }
}
foreach (array(1, 2, 3, 4, 5) as $v) {
    print "$v\n";
}
Copy after login
//foreach
$tar = array(
    1 => &#39;东&#39;,
    2 => &#39;西&#39;,
    3 => &#39;南&#39;,
    4 => &#39;北&#39;,
    5 => &#39;东南&#39;,
    6 => &#39;西南&#39;,
    7 => &#39;东北&#39;,
    8 => &#39;西北&#39;,
    9 => &#39;南北&#39;,
    10 => &#39;东西&#39;,
);
$TM = &#39;西&#39;;
foreach ($tar as $v => $vv) {
    if ($vv == $TM) {
        echo $vv . &#39;-&#39; . $v . &#39;<br />&#39;;
        break;
    }
//echo $vv;
}
Copy after login

for

echo &#39;<br />&#39;;
for ($i = 1; $i <= count($tar); $i++) {
    if ($tar[$i] == $TM) {
        echo $tar[$i] . &#39;-&#39; . $i . &#39;<br />&#39;;
        break;
    }
}
Copy after login

总结:foreach与for结果是完全相同的,但在效率上foreach要胜与for,首页for需要知道数组长度再用$i++来操作,页foreach不需要知道数组长度可自动检测并输入key,和value。

相关推荐:

如何理解PHP中for与foreach两个循环结构遍历数组的区别

php中for循环遇上return的示例代码分享

The above is the detailed content of The usage and difference between for loop and foreach loop in PHP. For more information, please follow other related articles on the PHP Chinese website!

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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles