Difference between unset and array_splice in PHP deleting elements in array

  • 2021-07-10 19:00:35
  • OfStack

If you want to delete 1 element in an array, you can use unset directly, but the index of the array will not be rearranged:


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


The 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); 
?>

The result is:

Array ( [0] = > a [1] = > c [2] = > d )

Delete a specific element from an array


<?php
$arr2 = array(1,3, 5,7,8);
foreach ($arr2 as $key=>$value)
{
  if ($value === 3)
    unset($arr2[$key]);
}
var_dump($arr2);
?> 

Supplement and delete empty arrays

Example:


<?php
  $array = ('a' => "abc", 'b' => "bcd",'c' =>"cde",'d' =>"def",'e'=>"");
  array_filter($array);
  echo "<pre>";
  print_r($array);
?>


Results:

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

Summarize

If the array_splice () function is deleted, the index value of the array also changes.
If the unset () function is deleted, the index value of the array does not change.


Related articles: