php删除数组元素的二种方法 unset,array_splice用法区别

WBOY
Release: 2016-07-25 08:52:56
Original
1101 people have browsed it
  1. $arr = array('a','b','c','d');
  2. unset($arr[1]);
  3. print_r($arr);
  4. ?>
复制代码

结果: Array ( [0] => a [2] => c [3] => d ) 如何做到缺少的元素会被填补并且数组会被重新索引? 答案是array_splice():

例子:

  1. $arr = array('a','b','c','d');
  2. array_splice($arr,1,1);
  3. print_r($arr);
  4. ?>
复制代码

结果: Array ( [0] => a [1] => c [2] => d ) 删除数组中特定元素(bbs.it-home.org 脚本学堂):

  1. $arr2 = array(1,3, 5,7,8);
  2. foreach ($arr2 as $key=>$value)
  3. {
  4. if ($value === 3)
  5. unset($arr2[$key]);
  6. }
  7. var_dump($arr2);
  8. ?>
复制代码

删除空数组:

  1. $array = ('a' => "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");
  2. array_filter($array);
  3. echo "
    ";
    Copy after login
  4. print_r($array);
  5. ?>
复制代码

结果: Array ( [a] => abc => bcd [c] => cde [d] => def )

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



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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!