PHP
Filtering Associative Arrays by Multiple Conditions
Filter an array of associative arrays in PHP based on multiple user-defined criteria, allowing precise selection of data from complex datasets to meet specific requirements.
<?php
function filterAssociativeArray(array $array, callable $callback): array
{
return array_filter($array, $callback);
}
$products = [
['id' => 1, 'category' => 'Electronics', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'category' => 'Books', 'price' => 25, 'in_stock' => true],
['id' => 3, 'category' => 'Electronics', 'price' => 750, 'in_stock' => false],
['id' => 4, 'category' => 'Home', 'price' => 50, 'in_stock' => true],
['id' => 5, 'category' => 'Electronics', 'price' => 2000, 'in_stock' => true]
];
// Filter for electronics that are in stock and price less than 1500
$filteredProducts = filterAssociativeArray($products, function ($product) {
return $product['category'] === 'Electronics' &&
$product['in_stock'] === true &&
$product['price'] < 1500;
});
print_r($filteredProducts);
/*
Output:
Array
(
[0] => Array
(
[id] => 1
[category] => Electronics
[price] => 1200
[in_stock] => 1
)
)
*/
?>
How it works: This snippet demonstrates how to filter an array of associative arrays using `array_filter` with a custom callback function. The `filterAssociativeArray` function takes the array and a callable (which can be an anonymous function or a predefined function name). The callback function receives each item from the array and should return `true` if the item should be included in the filtered result, or `false` otherwise. This allows for highly flexible filtering based on any number of conditions applied to the item's properties.