Two ways to delete array elements in php. Differences in usage of unset and array_splice

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

Results: Array ( [0] => a [2] => c [3] => d ) How can the missing elements be filled and the array re-indexed? The answer is array_splice():

Example:

  1. $arr = array('a','b','c','d');
  2. array_splice($arr,1,1);
  3. print_r($arr) ;
  4. ?>
Copy code

Result: Array ( [0] => a [1] => c [2] => d ) Delete specific elements in the array (bbs.it-home.org Scripting School):

  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. ?>
Copy code

Delete empty arrays:

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

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

Summary: If the array_splice() function is deleted, the index value of the array will also change. If the unset() function deletes it, the index value of the array will not change.



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!