PHP's method of removing the contents of a particular array and reconstructing the index of an array.

  • 2020-03-31 21:39:19
  • OfStack

 
$a = array('a','b','c','d'); 
unset($a[2]); 
print_r($a); 

But the biggest drawback of this approach is that it does not rebuild the array index.

After looking up information. The original PHP provides this function. But very indirect..

This function is array_splice.

In order to use convenient. I packaged into a function. Convenient for everyone to use.
 
function array_remove(&$arr,$offset){ 
array_splice($arr,$offset,1); 
} 
$a = array('a','b','c','d'); 
array_remove($a,2); 
print_r($a); 

The test shows that the position of.2 is actually deleted and the index is re-established.

Related articles: