What is the difference between array_filter() and array_map() in PHP?

The main difference between array_filter() and array_map() in PHP is that array_filter() is used to filter elements of an array based on a specified callback function, while array_map() is used to apply a callback function to each element of an array and return a new array with the modified elements. To filter elements of an array using array_filter(), you need to provide a callback function that returns true for the elements you want to keep. On the other hand, to modify elements of an array using array_map(), you need to provide a callback function that will be applied to each element of the array.

// Using array_filter() to filter elements of an array
$numbers = [1, 2, 3, 4, 5];
$filteredNumbers = array_filter($numbers, function($num) {
    return $num % 2 == 0; // Keep only even numbers
});
print_r($filteredNumbers);

// Using array_map() to modify elements of an array
$numbers = [1, 2, 3, 4, 5];
$squaredNumbers = array_map(function($num) {
    return $num * $num; // Square each number
}, $numbers);
print_r($squaredNumbers);