There are multiple ways to remove an element from an array in PHP. The simplest one is the method unset()
.
unset()
The method unset()
can be used to remove a single element of the array:
$myArray = ['apple', 'banana', 'cherry', 'date'];
unset($myArray[1]); // Remove the element at index 1 (banana)
$myArray = array_values($myArray); // Re-index the array if you want to remove the gap
print_r($myArray);
The output of print_r()
is:
Array
(
[0] => 'apple'
[1] => 'cherry'
[2] => 'date'
)
array_splice()
This function can be used to remove a portion of an array and replace it with something else. If you want to remove a single element, you can specify a length of 1:
$myArray = ['apple', 'banana', 'cherry', 'date'];
array_splice($myArray, 1, 1); // Remove 1 element starting from index 1
print_r($myArray);
array_diff()
You can use this function to create a new array with all the elements of the first array that are not in the other arrays:
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$myArray = array_diff($myArray, [$elementToRemove]);
print_r($myArray);
array_filter()
This function can be used with a callback function to filter elements from an array:
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$myArray = array_filter($myArray, function($value) use ($elementToRemove) {
return $value !== $elementToRemove;
});
print_r($myArray);
unset()
with array_search()
You can combine unset()
with array_search()
to remove an element based on its value:
$myArray = ['apple', 'banana', 'cherry', 'date'];
$elementToRemove = 'banana';
$index = array_search($elementToRemove, $myArray);
if ($index !== false) {
unset($myArray[$index]);
}
print_r($myArray);