PHP
Filtering PHP Arrays with a Callback Function
Learn how to selectively remove elements from a PHP array by applying a custom callback function, perfect for data cleansing and matching specific criteria for your web projects.
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter out even numbers
$oddNumbers = array_filter($numbers, function($number) {
return $number % 2 != 0;
});
print_r($oddNumbers);
// Filter an associative array based on a value condition
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75],
['name' => 'Monitor', 'price' => 300],
];
$expensiveProducts = array_filter($products, function($product) {
return $product['price'] > 100;
});
print_r($expensiveProducts);
?>
How it works: The `array_filter()` function iterates over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the value is included in the new filtered array; otherwise, it's excluded. This allows for highly flexible and dynamic filtering logic, essential for data processing in web applications.