1.5K
Removing elements from PHP array
There are multiple was by which we can delete element from a PHP array.
unset()
Code:
$arraylist = [0 => "x", 1 => "y", 2 => "z"];
unset($arraylist[1]); // Key which you want to delete
Output:
[
[0] => x
[2] => z
]
Unset doesn’t reset the array keys. In order to reset the array keys we will have to use array_values()
after unset function.
array_splice()
Code:
$arraylist = [0 => "x", 1 => "y", 2 => "z"];
array_splice($arraylist, 1, 1); //(Array, offset, length)
Output:
[
[0] => x
[1] => z
]
It uses array offset and not the keys.
If you use array_splice()
the keys will automatically be reindexed, but the associative keys won’t change — as opposed to array_values()
, which will convert all keys to numerical keys.