關於array_shift

前幾天用到array_shift這個函數,發現得到的結果並非是自己所預想的,後來又仔細看了下PHP Manual,發現了其中的原因(注意黑體部分):
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. If array is empty (or is not an array), NULL will be returned.
我沒有得到預期結果的原因正是因爲我進行array_shift的數組的鍵是數字型(numerical)的,進行array_shift後,鍵值已不再是原始的鍵值。
示例代碼如下:
<?php
$arr = array('name' => 'wong', 'age' => 24, 'sex' => 'male');
print_r($arr);
array_shift($arr);
print_r($arr);

$arr = array(45 => 'wong', 46 => 24, 47 => 'male');
print_r($arr);
array_shift($arr);
print_r($arr);

/*
Output:
Array
(
    [name] => wong
    [age] => 24
    [sex] => male
)
Array
(
    [age] => 24
    [sex] => male
)
Array
(
    [45] => wong
    [46] => 24
    [47] => male
)
Array
(
    [0] => 24
    [1] => male
)
*/
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章