PHP

Filter Associative Arrays by Custom Condition

Efficiently filter a PHP array of associative arrays based on a user-defined condition using `array_filter` and a callback function to refine data.

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

$expensiveElectronics = array_filter($products, function($product) {
    return $product['category'] === 'Electronics' && $product['price'] > 100;
});

print_r($expensiveElectronics);
?>
How it works: This snippet demonstrates how to filter an array of associative arrays. `array_filter` iterates over each element, and the anonymous function acts as a callback, returning `true` for elements that should be included in the result and `false` otherwise. Here, it filters for electronics products costing more than 100, providing a flexible way to select specific data subsets.

Need help integrating this into your project?

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

Hire DigitalCodeLabs