PHP

Filtering an Array by Multiple Dynamic Conditions

Efficiently filter an array of associative arrays using multiple, dynamic conditions. Ideal for advanced search or complex data filtering tasks in web applications.

<?php
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 3, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 4, 'name' => 'Desk Chair', 'category' => 'Furniture', 'price' => 300],
    ['id' => 5, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 450],
];

/**
 * Filters an array of associative arrays based on multiple key-value conditions.
 * Each item must match all provided conditions to be included.
 */
function filterArrayByConditions(array $array, array $conditions): array {
    return array_filter($array, function($item) use ($conditions) {
        foreach ($conditions as $key => $value) {
            if (!isset($item[$key]) || $item[$key] !== $value) {
                return false; // Mismatch found for one condition
            }
        }
        return true; // All conditions matched
    });
}

// Example 1: Filter for specific category AND price
$filteredProducts1 = filterArrayByConditions($products, ['category' => 'Electronics', 'price' => 75]);
echo "Products matching category 'Electronics' AND price '75':
";
print_r($filteredProducts1);

// Example 2: Filter with a custom callback for range conditions
$expensiveElectronics = array_filter($products, function($product) {
    return $product['category'] === 'Electronics' && $product['price'] > 100;
});
echo "Expensive electronics (category 'Electronics' AND price > 100):
";
print_r($expensiveElectronics);
?>
How it works: This snippet demonstrates how to filter an array of associative arrays using custom logic. The `filterArrayByConditions` function allows you to apply multiple key-value conditions dynamically. The second example shows a direct `array_filter` usage with a more complex callback for filtering based on a range or combination of criteria, offering flexible data subsetting for tasks like search or advanced filtering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs