How can array_filter() be used to efficiently remove unwanted elements from an array in PHP?

To efficiently remove unwanted elements from an array in PHP, you can use the array_filter() function. This function allows you to iterate over each element in the array and apply a callback function to determine whether the element should be included in the filtered array. By providing a callback function that returns true for elements you want to keep and false for elements you want to remove, you can easily filter out unwanted elements from the array.

// Define an array with unwanted elements
$array = [1, 2, 3, 4, 5];

// Define a callback function to filter out even numbers
$filteredArray = array_filter($array, function($value) {
    return $value % 2 != 0;
});

// Output the filtered array
print_r($filteredArray);