php循环语句 for()与foreach()用法区别介绍_PHP
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











Kernelsecuritycheckfailure (kernel check failure) is a relatively common type of stop code. However, no matter what the reason is, the blue screen error causes many users to be very distressed. Let this site carefully introduce 17 types to users. Solution. 17 solutions to kernel_security_check_failure blue screen Method 1: Remove all external devices When any external device you are using is incompatible with your version of Windows, the Kernelsecuritycheckfailure blue screen error may occur. To do this, you need to unplug all external devices before trying to restart your computer.

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values swapped. $original_array=[

Can Win10 skype be uninstalled? This is a question that many users want to know, because many users find that this application is included in the default program on their computers, and they are worried that deleting it will affect the operation of the system. Let this website help users Let’s take a closer look at how to uninstall Skype for Business in Win10. How to uninstall Skype for Business in Win10 1. Click the Windows icon on the computer desktop, and then click the settings icon to enter. 2. Click "Apply". 3. Enter "Skype" in the search box and click to select the found result. 4. Click "Uninstall". 5

How to use for to find n factorial: 1. Use the "for (var i=1;i<=n;i++){}" statement to control the loop traversal range to "1~n"; 2. In the loop body, use "cj *=i" Multiply the numbers from 1 to n, and assign the product to the variable cj; 3. After the loop ends, the value of the variable cj is the factorial of n, and then output it.

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element
