Reindexing Method for Deleting Elements in php Array

  • 2021-07-18 07:41:13
  • OfStack

If you want to delete an element in an array, you can use unset directly, but what I saw today surprised me.


<?php
$arr = array('a','b','c','d');
unset($arr[1]);
print_r($arr);
?>

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

So how can we make sure that the missing elements are filled and the array is re-indexed? The answer is

array_splice():


<?php
$arr = array('a','b','c','d');
array_splice($arr,1,1);
print_r($arr);
?>

After print_r ($arr), the result is A (www. ofstack. com) rray ([0] = > a [1] = > c [2] = > d )

Delete the specified element of the array

array_search () is more practical

The array_search () function looks up a key value in an array like in_array () 1. If the value is found, the key name of the matching element will be returned. If not found, false is returned


$array = array('1', '2', '3', '4', '5');
$del_value = 3;
unset($array[array_search($del_value , $array)]);// Utilization unset Delete this element
print_r($array);

Output
array('1', '2', '4', '5');

However, if you want to re-index the array, you need to use foreach to traverse the deleted array and then re-create an array.


Related articles: