标签:
如果要在某个数组中删除一个元素,可以直接用的unset,但是数组的索引不会重排:
1 2 3 4 5 | <?php $arr = array ( ‘a‘ , ‘b‘ , ‘c‘ , ‘d‘ ); unset( $arr [1]); print_r( $arr ); ?> |
结果是:
Array ( [0] => a [2] => c [3] => d )
那么怎么才能做到缺少的元素会被填补并且数组会被重新索引呢?答案是array_splice():
1 2 3 4 5 | <?php $arr = array ( ‘a‘ , ‘b‘ , ‘c‘ , ‘d‘ ); array_splice ( $arr ,1,1); print_r( $arr ); ?> |
结果是:
Array ( [0] => a [1] => c [2] => d )
删除数组中特定元素
1 2 3 4 5 6 7 8 9 | <?php $arr2 = array (1,3, 5,7,8); foreach ( $arr2 as $key => $value ) { if ( $value === 3) unset( $arr2 [ $key ]); } var_dump( $arr2 ); ?> |
补充删除空数组
实例:
1 2 3 4 5 6 | <?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删除数组中元素的区别
标签:
原文地址:http://www.cnblogs.com/muxiaoye/p/7c2b099fda11de555dc6e9d01bccdeb8.html