the internal array pointer

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value)     statement

foreach (array_expression as $key => $value)     statement

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one

(so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration. It is possible to customize object iteration.

 

Note: In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

 

foreach 语法结构提供了遍历数组(E iterate over arrays)的简单方式。 foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出(E issue)错误信息。

第一种格式遍历(E loop over )给定的 array_expression 数组。 每次循环中(E on each iteration),当前(E current)单元的值被赋给(E is assiged) $value 并且数组内部的指针(E the inernal array pointer)向前移一步(因此下一次循环中将会得到下一个单元)。 当 foreach 开始执行时,数组内部的指针会自动指向第一个单元。 这意味着不需要在 foreach 循环之前调用 reset()。

 

 1 <?php
 2 $arr = array(1,2,3,4);
 3 var_dump($value);//null
 4 foreach($arr as &$value){
 5     $value = $value*2;
 6 }
 7 var_dump($value);//8
 8 var_dump($arr);// 2 4 6 8
 9 
10 $arrb = array(1,2,3,4);
11 var_dump($valueb);//null
12 foreach($arrb as $valueb){
13     $valueb = $valueb*2;
14 }
15 var_dump($valueb);//8
16 var_dump($arrb);//1 2 3 4 

 

posted @ 2016-09-10 17:39  papering  阅读(279)  评论(0编辑  收藏  举报