search
HomeBackend DevelopmentPHP TutorialThe usage and difference between for loop and foreach loop in PHP

本篇文章我们来讲讲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++) ;

当然,第一个例子看上去最正常(或者第四个),但你可能会发现在 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";
}

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

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";
}

示范用法的更多例子:

$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";
}
//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;
}

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;
    }
}

总结: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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment