Differences between unset and array_splice in PHP to delete elements in an array
It is very simple to delete array elements in php. However, sometimes we need to sort indexes to delete arrays. We will use related functions. Here we will introduce the use of unset, what is the difference between array_splice and deleting elements in an array?
If you want to delete an element from an array, you can use unset directly, but the index of the array will not be rearranged:
$ 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 fill in the missing elements and re-index the array? The answer is array_splice ():
$ 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 special elements in an array
$ Arr2 = array (1, 3, 5, 7, 8 );
Foreach ($ arr2 as $ key => $ value)
{
If ($ value = 3)
Unset ($ arr2 [$ key]);
}
Var_dump ($ arr2 );
?>
Add or delete an empty array
Instance:
$ Array = ('A' => "abc", 'B' => "bcd", 'c' => "cde", 'D' => "def ", 'E' => "");
Array_filter ($ array );
Echo"
";
Print_r ($ array );
?>
Result:
Array (
[A] => abc
[B] => bcd
[C] => cde
[D] => def
)
Summary
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 remains unchanged.