PHP next

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

2.函数的参数:数组

  @param array &$array函数

3.spa

例子一:数组拷贝时,内部指针的位置也一块儿拷贝3d

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) ;

 例子三:code

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";

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

1)指针重置的状况:element

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)指针未重置的状况:it

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 的元素。

相关文章
相关标签/搜索