PHP
Filter an Array by Custom Criteria in PHP
Learn how to filter PHP arrays using a custom callback function with `array_filter` to keep only elements meeting specific conditions, enhancing data manipulation.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
['name' => 'Book', 'price' => 15, 'category' => 'Books'],
['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics']
];
// Filter products with price greater than $100
$expensiveProducts = array_filter($products, function($product) {
return $product['price'] > 100;
});
echo "<pre>";
print_r($expensiveProducts);
echo "</pre>";
// Output will contain products with Laptop, Monitor, Keyboard
?>
How it works: The `array_filter()` function iterates over each element in the `$products` array, applying the provided anonymous function. If the anonymous function returns `true`, the element is included in the new `$expensiveProducts` array; otherwise, it's excluded. This allows for flexible filtering based on any custom condition, making it highly useful for refining data sets.