PHP中unset,array_splice刪除數組中元素的區別

來源:互聯網
上載者:User

標籤:abc   val   filter   個數   dump   總結   each   splice   too   

php中刪除數組元素是非常的簡單的,但有時刪除數組需要對索引進行一些排序要求我們會使用到相關的函數,這裡我們來介紹使用unset,array_splice刪除數組中的元素區別吧

如果要在某個數組中刪除一個元素,可以直接用的unset,但是數組的索引不會重排:

<?php $arr  array ( ‘a‘ , ‘b‘ , ‘c‘ , ‘d‘ ); unset( $arr [1]); print_r( $arr ); ?>

 

結果是:

Array ( [0] => a [2] => c [3] => d )
 
那麼怎麼才能做到缺少的元素會被填補並且數組會被重新索引呢?答案是array_splice():

<?php $arr  array ( ‘a‘ , ‘b‘ , ‘c‘ , ‘d‘ );  array_splice ( $arr ,1,1); print_r( $arr ); ?>

結果是:
Array ( [0] => a [1] => c [2] => d )

 
刪除數組中特定元素

<?php $arr2  array (1,3, 5,7,8); foreach  ( $arr2  as  $key => $value ) {    if  ( $value  === 3)      unset( $arr2 [ $key ]); } var_dump( $arr2 ); ?> 

補充刪除空數組

執行個體:

<?php    $array  = ( ‘a‘  =>  "abc" ‘b‘  =>  "bcd" , ‘c‘  => "cde" , ‘d‘  => "def" , ‘e‘ => "" );    array_filter ( $array );    echo  "<pre>" ;    print_r( $array ); ?>

 

結果:

Array ( 
     [a] => abc 
     [b] => bcd 
     [c] => cde 
     [d] => def
)

總結
 

array_splice()函數刪除的話,數組的索引值也變化了。
unset()函數刪除的話,數組的索引值沒有變化。

PHP中unset,array_splice刪除數組中元素的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.