PHP

Filter Associative Arrays with Custom Conditions

Efficiently filter elements from an associative array based on complex, user-defined conditions using PHP's `array_filter` function and a callback.

$products = [
    ['id' => 101, 'name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['id' => 102, 'name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['id' => 103, 'name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['id' => 104, 'name' => 'Desk Chair', 'price' => 200, 'category' => 'Furniture'],
];

// Filter products with price > 100 AND category is 'Electronics'
$filteredProducts = array_filter($products, function($product) {
    return $product['price'] > 100 && $product['category'] === 'Electronics';
});

print_r($filteredProducts);

// Filter products where 'name' contains 'key' (case-insensitive)
$searchKeyword = 'key';
$productsWithKeyword = array_filter($products, function($product) use ($searchKeyword) {
    return stripos($product['name'], $searchKeyword) !== false;
});

print_r($productsWithKeyword);
How it works: The `array_filter()` function iterates over each element of an array, passing it to a user-defined callback function. If the callback returns `true`, the element is included in the resulting filtered array; otherwise, it's excluded. This allows for highly flexible filtering based on any custom logic involving multiple conditions or string operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs