PHP
Filter Associative Arrays by Multiple Dynamic Criteria
Discover how to selectively filter elements from an array of associative arrays by applying several dynamic conditions simultaneously using a flexible custom callback function.
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25, 'in_stock' => false],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75, 'in_stock' => true],
['id' => 4, 'name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 20, 'in_stock' => true],
['id' => 5, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 60, 'in_stock' => true]
];
$filteredProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics' &&
$product['price'] < 1000 &&
$product['in_stock'] === true;
});
print_r($filteredProducts);
How it works: This snippet utilizes the `array_filter()` function with an anonymous callback. For each associative array element in the `$products` array, the callback function evaluates multiple conditions (e.g., category, price, and stock status). Only elements for which the callback returns `true` are included in the `$filteredProducts` array, allowing for precise data selection based on complex rules.