How does the array_filter function work in PHP and how can it be used to filter out specific elements?
The array_filter function in PHP is used to filter elements from an array based on a specified callback function. The callback function should return true for the elements to be kept in the filtered array and false for the elements to be removed. By using array_filter, specific elements can be easily filtered out from the array.
// Example of using array_filter to filter out specific elements from an array
$numbers = [1, 2, 3, 4, 5, 6];
// Filter out even numbers from the array
$filteredNumbers = array_filter($numbers, function($num) {
return $num % 2 != 0;
});
print_r($filteredNumbers); // Output: Array ( [0] => 1 [2] => 3 [4] => 5 )