码迷,mamicode.com
首页 > Web开发 > 详细

PHP next

时间:2017-06-23 10:13:19      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:输出   div   int   php   element   数组   color   错误   value   

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

PHP next

标签:输出   div   int   php   element   数组   color   错误   value   

原文地址:http://www.cnblogs.com/jingjingdidunhe/p/7068122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!