PHP

Filter Associative Array Collection by Multiple Custom Criteria in PHP

Apply multiple filtering conditions to an array of associative arrays in PHP using `array_filter` with a custom callback, enabling precise and complex data selection.

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

// Filter products that are 'Electronics', 'in_stock', AND have a price greater than 50
$filteredProducts = array_filter($products, function($product) {
    return $product['category'] === 'Electronics' &&
           $product['in_stock'] === true &&
           $product['price'] > 50;
});

print_r($filteredProducts);
/* Expected output for $filteredProducts:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Laptop
            [category] => Electronics
            [price] => 1200
            [in_stock] => 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => Keyboard
            [category] => Electronics
            [price] => 75
            [in_stock] => 1
        )

    [4] => Array
        (
            [id] => 5
            [name] => Monitor
            [category] => Electronics
            [price] => 250
            [in_stock] => 1
        )
)
*/

// Filter products that are 'Furniture' OR have a price less than 100
$alternativeFilter = array_filter($products, function($product) {
    return $product['category'] === 'Furniture' ||
           $product['price'] < 100;
});

print_r($alternativeFilter);
?>
How it works: This snippet demonstrates how to use PHP's `array_filter()` function with an anonymous callback to apply multiple, custom filtering conditions to an array of associative arrays. The callback function defines the specific logic for inclusion, allowing you to combine conditions using logical operators (`&&` for AND, `||` for OR) to precisely select elements that meet all (or any) specified criteria, making it highly versatile for data querying and refinement.

Need help integrating this into your project?

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

Hire DigitalCodeLabs