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