PHP
Filter an Associative Array by Multiple Custom Conditions
Learn to filter PHP associative arrays using `array_filter` with a custom callback function that applies multiple validation rules.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'name' => 'Mouse', 'price' => 25, 'in_stock' => true],
['id' => 3, 'name' => 'Keyboard', 'price' => 75, 'in_stock' => false],
['id' => 4, 'name' => 'Monitor', 'price' => 300, 'in_stock' => true],
['id' => 5, 'name' => 'Webcam', 'price' => 50, 'in_stock' => true],
];
// Filter for products in stock AND price less than 100
$filteredProducts = array_filter($products, function($product) {
return $product['in_stock'] === true && $product['price'] < 100;
});
print_r($filteredProducts);
/*
Output will be:
Array
(
[1] => Array
(
[id] => 2
[name] => Mouse
[price] => 25
[in_stock] => 1
)
[4] => Array
(
[id] => 5
[name] => Webcam
[price] => 50
[in_stock] => 1
)
)
*/
?>
How it works: This snippet demonstrates how to use the `array_filter` function to select elements from an array based on multiple custom conditions. It passes an anonymous function (callback) to `array_filter` which returns `true` only if both `in_stock` is true and `price` is less than 100 for a given product. This allows for powerful and flexible filtering logic.