How can array_filter() be used to efficiently remove elements from an array in PHP?
When we want to efficiently remove elements from an array in PHP, we can use the array_filter() function. This function allows us to iterate over the array and apply a callback function to each element. If the callback function returns true, the element is kept in the array; if it returns false, the element is removed. This provides a clean and efficient way to filter out unwanted elements from an array.
// Example of using array_filter() to efficiently remove elements from an array
$array = [1, 2, 3, 4, 5];
// Remove all even numbers from the array
$array = array_filter($array, function($element) {
return $element % 2 != 0;
});
print_r($array); // Output: [1, 3, 5]