Home  >  Article  >  Backend Development  >  How to rebuild index after deleting elements from php array?

How to rebuild index after deleting elements from php array?

WBOY
WBOYOriginal
2016-07-25 08:52:251084browse
  1. $arr = array('a','b','c','d');
  2. unset($arr[1]);
  3. print_r($arr);
  4. ?>
After copying the code

print_r($arr), the result is not like that. The final result is Array ( [0] => a [2] => c [3] => d )

How can missing elements be filled and the array re-indexed?

Use array_splice():

  1. $arr = array('a','b','c','d');
  2. array_splice($arr,1,1);
  3. print_r($arr) ;
  4. ?>
  5. After print_r($arr), the result is A(bbs.it-home.org)rray ( [0] => a [1] => c [2] => d )
Copy code

2, delete the specified element of the array array_search() is more practical The array_search() function, like in_array(), searches for a key value in an array. If the value is found, the key of the matching element is returned. If not found, return false

  1. $array = array('1', '2', '3', '4', '5');
  2. $del_value = 3;
  3. unset($array[array_search($del_value , $ array)]);//Use unset to delete this element
  4. print_r($array);
Copy code

output array('1', '2', '4', '5'); If you want to re-index the array, you need to use foreach to traverse the deleted array and then re-create an array.



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