zoukankan      html  css  js  c++  java
  • 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) ."'
    ";
    6 echo "Pointer of arr2 is " .key($arr2) .". The value is '" . current($arr1) ."'
    ";

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

    1 <?php
    2 $arr1 = ['last','next'];
    3 foreach($arr1 as $key => $value){
    4     echo "Number $key's  value : $value
    ";
    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) . "
    ";
    7 echo "The pointer's position of the array of arr1 is " .key($arr2) . "
    ";

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

    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)."
    ";
    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)."
    ";
    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!
    ";
    6 }else{
    7     echo "The element doesn't exist!
    ";
    8 }

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

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

     

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

    学习记录,方便复习
  • 相关阅读:
    索引
    排序---冒泡排序、快速排序、选择排序、插入排序、希尔排序
    设计模式6大原则
    InputStream的read()读取机制
    Java中的关键字---native
    Java中的关键字---static
    Java中的关键字---transient
    负载均理解
    2020-03-29 微服务网关GateWay
    2020-03-28 微服务网关Zuul
  • 原文地址:https://www.cnblogs.com/jingjingdidunhe/p/7068122.html
Copyright © 2011-2022 走看看