php--------刪除數組的第一個元素和最後一個元素

來源:互聯網
上載者:User

標籤:col   一個   元素   post   user   result   長度   pop   過程   

對於一個php數組,該如何刪除該數組的第一個元素或者最後一個元素呢?其實這兩個過程都可以通過php內建的函數 array_pop 和 array_shift 來完成,下面就具體介紹一下如何來操作。

(1)使用 array_pop 刪除數組的最後一個元素,例如:

$user=array(‘apple‘,‘banana‘,‘orange‘);$result=array_pop($user);print_r($result);print_r($user);

 

結果將是:

orange
array(‘apple‘,‘banana‘)

(2)使用 array_shift 刪除數組的第一個元素,例如:

 

$user=array(‘apple‘,‘banana‘,‘orange‘);$result=array_shift($user);print_r($result);print_r($user);

 

結果將是:

apple
array(‘banana‘,‘orange‘)

其實刪除數組的第一個元素還可以使用 array_splice 這個函數,即:

 

 

$user=array_splice($user,1); //刪除數組第一個元素,注意此時返回的是被刪除後的新的數組

 

 

下面簡單的對 array_pop 和 array_shift 做一下解釋:

array_pop() 彈出並返回 array 數組的最後一個單元,並將數組 array 的長度減一。如果 array 為空白(或者不是數組)將返回 NULL。

array_shift() 將 array 的第一個單元移出並作為結果返回,將 array 的長度減一併將所有其它單元向前移動一位。所有的數字鍵名將改為從零開始計數,文字鍵名將不變。如果 array 為空白(或者不是數組),則返回 NULL。

 

php--------刪除數組的第一個元素和最後一個元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.