PHP

Filter an Array of Associative Arrays by Multiple Criteria

Create a flexible function to filter a list of associative arrays based on multiple dynamic conditions (e.g., price range, category, status) using array_filter.

<?php

$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200, 'status' => 'in_stock'],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25, 'status' => 'in_stock'],
    ['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75, 'status' => 'low_stock'],
    ['id' => 4, 'name' => 'Desk', 'category' => 'Furniture', 'price' => 300, 'status' => 'out_of_stock'],
    ['id' => 5, 'name' => 'Chair', 'category' => 'Furniture', 'price' => 150, 'status' => 'in_stock'],
    ['id' => 6, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 400, 'status' => 'in_stock']
];

function filterProducts(array $products, array $criteria): array
{
    return array_filter($products, function ($product) use ($criteria) {
        foreach ($criteria as $key => $value) {
            // Handle different comparison types (e.g., exact match, range)
            if ($key === 'price_min' && $product['price'] < $value) {
                return false;
            }
            if ($key === 'price_max' && $product['price'] > $value) {
                return false;
            }
            if ($key !== 'price_min' && $key !== 'price_max' && $product[$key] !== $value) {
                return false; // Mismatch for other exact match criteria
            }
        }
        return true; // All criteria matched
    });
}

// Example 1: Filter by category 'Electronics' and status 'in_stock'
$filteredElectronics = filterProducts($products, [
    'category' => 'Electronics',
    'status' => 'in_stock'
]);

echo "Products (Electronics, In Stock):
";
print_r($filteredElectronics);

// Example 2: Filter by category 'Furniture' and price less than or equal to 200
$filteredFurniture = filterProducts($products, [
    'category' => 'Furniture',
    'price_max' => 200
]);

echo "
Products (Furniture, Price <= 200):
";
print_r($filteredFurniture);

?>
How it works: This snippet provides a flexible function `filterProducts` that can filter an array of associative arrays based on multiple, dynamic criteria. It uses `array_filter()` with an anonymous callback function. The callback iterates through the `$criteria` array, checking each product against the specified conditions. It supports exact matches for keys like 'category' and 'status', and also includes basic range filtering for 'price' (using 'price_min' and 'price_max'). If a product fails any of the criteria, the callback returns `false`, causing `array_filter()` to exclude it. If all criteria are met, it returns `true`, and the product is included in the result.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs