we have soo many methods to delete an element from an array in php but the most common or mostly used methos are-
- unset() = This function takes an element as a parameter and unset it. It wouldn’t change the keys of other elements.
- array_splice() =This function takes parameters an array, offset[where to start] and length. It will automatically re-index an indexed array but not an associated array after deleting the elements.
- array_diff() = This function takes an array and list of array values as input and deletes the giving values from an array.
example
<?php
// with unset()
$cities= ["bangalore","gwalior","delhi"];
unset($cities[2]);
echo "<pre>";
print_r($cities);
echo "</pre>";
// with array_splice()
$cities= ["bangalore","gwalior","delhi"];
array_splice($cities,1,2);
echo "<pre>";
print_r($cities);
echo "</pre>";
// with array_diff()
$cities= ["bangalore","gwalior","delhi"];
$cities=array_diff($cities,["gwalior"]);
echo "<pre>";
print_r($cities);
echo "</pre>";
?>
output
Array
(
[0] => bangalore
[1] => gwalior
)
Array
(
[0] => bangalore
)
Array
(
[0] => bangalore
[2] => delhi
)