


The 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 => '东', 2 => '西', 3 => '南', 4 => '北', 5 => '东南', 6 => '西南', 7 => '东北', 8 => '西北', 9 => '南北', 10 => '东西', ); $TM = '西'; foreach ($tar as $v => $vv) { if ($vv == $TM) { echo $vv . '-' . $v . '<br />'; break; } //echo $vv; }
for
echo '<br />'; for ($i = 1; $i <= count($tar); $i++) { if ($tar[$i] == $TM) { echo $tar[$i] . '-' . $i . '<br />'; break; } }
总结:foreach与for结果是完全相同的,但在效率上foreach要胜与for,首页for需要知道数组长度再用$i++来操作,页foreach不需要知道数组长度可自动检测并输入key,和value。
相关推荐:
如何理解PHP中for与foreach两个循环结构遍历数组的区别
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!

This tutorial provides detailed instructions on how to add a "Submit Quotation" button to each article in WordPress in a custom article type list. After clicking, a custom HTML form with the article ID pops up, and the form data is AJAX submission and success message display. The content covers front-end jQuery UI pop-up settings, dynamic data transfer, AJAX request processing, as well as back-end WordPress AJAX hook and data processing PHP implementation, ensuring complete functions, secure and good user experience.

This tutorial details how to add a Submit Quotation button to the list item of each custom post type (such as "Real Estate") in WordPress, and a custom HTML form with a specific post ID pops up after clicking it. The article will cover how to create modal popups using jQuery UI Dialog, dynamically pass the article ID through data attributes, and use WordPress AJAX mechanism to implement asynchronous submission of forms, while processing file uploads and displaying submission results, thus providing a seamless user experience.

This tutorial details how to implement a pop-up form for each article's custom button in the WordPress custom article type list page. The article will cover how to create pop-ups using jQuery UI Dialog, pass the article ID through data attributes, submit form data using AJAX, and process form submissions (including file uploads) in the WordPress backend, and return processing results. This guide is designed to provide a complete, actionable solution to enhance the user interaction experience.

This tutorial will provide detailed instructions on how to implement a pop-up submission form in WordPress for a standalone button for each custom post (such as the "Real Estate" type). We will use jQuery UI Dialog to create modal boxes and dynamically pass the article ID through JavaScript. Additionally, the tutorial will cover how to submit form data via AJAX and handle backend logic without refreshing the page, including file uploads and result feedback.

This article explores the common unlimited page refresh problem in PHP form submissions and provides solutions. This highlights how to correctly use $_POST to get form data, optimize the placement of PHP code to ensure successful redirection, and emphasizes the importance of adopting security practices in user authentication, such as avoiding hard-coded passwords, thereby building robust and secure web applications.

This article aims to solve the common problem of page automatic refresh in PHP form submission, and explores in-depth the correct way to obtain form data ($_POST) in PHP, the importance of code execution order, and how to achieve effective page redirection. In addition, the article highlights the key considerations in building a secure login system, including avoiding hard-coded passwords and adopting a more secure authentication mechanism, providing developers with the professional guidance needed to build stable and secure web applications.

This article explores in-depth the common page refresh issues in PHP form submission and provides effective solutions. The core is to use $_POST correctly to get form data, put PHP processing logic before HTML output, and emphasize that when using header() for page redirection, be sure to follow exit() or die() to ensure that the script terminates immediately. In addition, the article briefly mentions the importance of login form security, providing developers with guidance on building robust web applications.

This tutorial details how to achieve more granular inventory management in WooCommerce with custom code. Unlike WooCommerce's default "Hide Out of Stock" setting, we'll learn how to hide all variants of a variable from the catalog only when they are out of stock, and how to hide out of stock simple items, thereby optimizing the display and user experience of the store catalog.


Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Atom editor mac version download
The most popular open source editor

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

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.