Home >php教程 >php手册 >PHP中unset,array_splice删除数组中元素的区别

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

WBOY
WBOYOriginal
2016-06-13 09:28:02877browse

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

   php中删除数组元素是非常的简单的,但有时删除数组需要对索引进行一些排序要求我们会使用到相关的函数,这里我们来介绍使用unset,array_splice删除数组中的元素区别吧

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

  

  $arr = array('a','b','c','d');

  unset($arr[1]);

  print_r($arr);

  ?>

  结果是:

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

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

  

  $arr = array('a','b','c','d');

  array_splice($arr,1,1);

  print_r($arr);

  ?>

  结果是:

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

  删除数组中特定元素

  

  $arr2 = array(1,3, 5,7,8);

  foreach ($arr2 as $key=>$value)

  {

  if ($value === 3)

  unset($arr2[$key]);

  }

  var_dump($arr2);

  ?>

  补充删除空数组

  实例:

  

  $array = ('a' => "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");

  array_filter($array);

  echo "

";<p> </p>
<p>  print_r($array);</p>
<p>  ?></p>
<p>  结果:</p>
<p>  Array (</p>
<p>  [a] => abc</p>
<p>  [b] => bcd</p>
<p>  [c] => cde</p>
<p>  [d] => def</p>
<p>  )</p>
<p>  总结</p>
<p>  array_splice()函数删除的话,数组的索引值也变化了。</p>
<p>  unset()函数删除的话,数组的索引值没有变化。</p>
Statement:
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