Home > Backend Development > PHP Tutorial > PHP中unset,array_splice删除数组中元素的区别_PHP

PHP中unset,array_splice删除数组中元素的区别_PHP

WBOY
Release: 2016-06-01 11:50:35
Original
1153 people have browsed it

如果要在某个数组中删除一个元素,可以直接用的unset,但是数组的索引不会重排:

<&#63;php 
$arr = array('a','b','c','d');
unset($arr[1]);
print_r($arr);
&#63;>
Copy after login


结果是:

Array ( [0] => a [2] => c [3] => d )

那么怎么才能做到缺少的元素会被填补并且数组会被重新索引呢?答案是array_splice():

<&#63;php 
$arr = array('a','b','c','d'); 
array_splice($arr,1,1); 
print_r($arr); 
&#63;>
Copy after login

结果是:

Array ( [0] => a [1] => c [2] => d )

删除数组中特定元素

<&#63;php
$arr2 = array(1,3, 5,7,8);
foreach ($arr2 as $key=>$value)
{
  if ($value === 3)
    unset($arr2[$key]);
}
var_dump($arr2);
&#63;> 
Copy after login

补充删除空数组

实例:

<&#63;php
  $array = ('a' => "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");
  array_filter($array);
  echo "<pre class="brush:php;toolbar:false">";
  print_r($array);
&#63;>
Copy after login


结果:

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

总结
 

array_splice()函数删除的话,数组的索引值也变化了。
unset()函数删除的话,数组的索引值没有变化。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template