PHP
Filtering PHP Arrays with a Custom Callback
Learn how to filter elements from a PHP array using `array_filter` and a custom callback function, allowing precise data selection based on your specific criteria and logic.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['id' => 2, 'name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
['id' => 3, 'name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
['id' => 4, 'name' => 'T-Shirt', 'price' => 20, 'category' => 'Apparel'],
['id' => 5, 'name' => 'Jeans', 'price' => 50, 'category' => 'Apparel']
];
// Filter products more expensive than $50
$expensiveProducts = array_filter($products, function($product) {
return $product['price'] > 50;
});
print_r($expensiveProducts);
// Filter products by category
$electronicProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics';
});
print_r($electronicProducts);
?>
How it works: The `array_filter()` function in PHP is used to iterate over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the current value from the input array is included in the result array; otherwise, it's excluded. This allows for highly flexible and dynamic filtering of array elements based on any custom condition.