What role does array_filter play in optimizing code for handling arrays in PHP?

When working with arrays in PHP, it's common to need to filter out certain elements based on specific criteria. This can be achieved using the array_filter function, which allows you to iterate over an array and only keep elements that satisfy a given callback function. By using array_filter, you can optimize your code by efficiently removing unwanted elements from an array without the need for complex loops or conditional statements.

// Example of using array_filter to remove all elements with a value less than 5
$array = [3, 6, 8, 2, 4, 7];
$filteredArray = array_filter($array, function($value) {
    return $value >= 5;
});

print_r($filteredArray);