PHP next

1.函数的作用:返回数组当前元素位置的下一个元素

2.函数的参数:

  @param array &$array

3.

例子一:数组拷贝时,内部指针的位置也一起拷贝

1 <?php
2 $arr1 = ['last','next'];
3 next($arr1);
4 $arr2 = $arr1;
5 echo "Pointer of arr1 is " .key($arr1) .". The value is '" . current($arr1) ."'\n";
6 echo "Pointer of arr2 is " .key($arr2) .". The value is '" . current($arr1) ."'\n";

 

例子二: foreach 之后数组内部指针的位置不重置

1 <?php
2 $arr1 = ['last','next'];
3 foreach($arr1 as $key => $value){
4     echo "Number $key's  value : $value\n";
5 }
6 $str = is_null(key($arr1));
7 echo "The current key of the array of arr1 is " . ($str ? 'null' : $str) ;

 例子三:

1 <?php
2 $arr1 = ['last','next'];
3 next($arr1);
4 $arr2 = array_values($arr1);
5 
6 echo "The pointer's position of the array of arr1 is " .key($arr1) . "\n";
7 echo "The pointer's position of the array of arr1 is " .key($arr2) . "\n";

 例子四:接下来是比较奇异的两个地方,传数组参数给函数,看看指针的位置的情况:

1)指针重置的情况:

1 <?php
2 function testPointerPosition($array){
3     echo "The current element of array in function is '" .current($array)."' and current key is " .key($array)."\n";
4 }
5 
6 $arr1 = ['last','next'];
7 next($arr1);
8 next($arr1);
9 testPointerPosition($arr1);

2)指针未重置的情况:

1 <?php
2 function testPointerPosition($array){
3     echo "The current element of array in function is '" .current($array)."' and current key is " .key($array)."\n";
4 }
5 
6 $arr1 = ['last','next'];
7 next($arr1);
8 testPointerPosition($arr1);

 

例子五:有的时候使用next()函数之后,你想判断该元素是不是存在,结果你这么用:

1 <?php
2 $arr = [1,false];
3 next($arr);
4 if(current($arr)){
5     echo "The element exist!\n";
6 }else{
7     echo "The element doesn't exist!\n";
8 }

刚好有个 false 元素,就有了错误的输出。所以应该这么用:

1 <?php
2 $arr = [1,false];
3 next($arr);
4 if(key($arr) === false){
5     echo "Current element doesn't exist!\n";
6 }else{
7     echo "Current element exist!\n";
8 }

 

记住用 “===” 符号。数组不会有键值为false的类型的,即使你初始化的时候,用false作键值,内部也会将其解释为 0,并覆盖先前的键值为 0 的元素。

posted @ 2017-06-23 07:59  GoodByeZ  阅读(168)  评论(0编辑  收藏  举报