php循环语句 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 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 ?>
当然,第一个例子看上去最正常(或者第四个),但你可能会发现在 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
\n";
}
foreach ($arr as $value) {
echo "Value: $value
\n";
}
?>
以下代码功能也完全相同:
复制代码 代码如下:
reset ($arr);
while (list($key, $value) = each ($arr)) {
echo "Key: $key; Value: $value
\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value
\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.'
';
break;
}
//echo $vv;
}
//西-2
//for
复制代码 代码如下:
echo '
';
for( $i=1;$i{
if( $tar[$i] == $TM )
{
echo $tar[$i].'-'.$i.'
';
break;
}
}
//西-2
总结:foreach与for结果是完全相同的,但在效率上foreach要胜与for,首页for需要知道数组长度再用$i++来操作,页foreach不需要知道数组长度可自动检测并输入key,和value。

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

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

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

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
