PHP
Filter Multidimensional Arrays by Multiple Criteria
Use `array_filter` with a custom callback to filter a PHP array of arrays or objects based on multiple conditions and complex logic.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25, 'in_stock' => true],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75, 'in_stock' => false],
['id' => 4, 'name' => 'Desk Chair', 'category' => 'Furniture', 'price' => 150, 'in_stock' => true],
['id' => 5, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300, 'in_stock' => true]
];
// Filter products: category 'Electronics', price less than 500, and in stock
$filteredProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics'
&& $product['price'] < 500
&& $product['in_stock'] === true;
});
// Another example: products that are either 'Electronics' OR 'Furniture' AND price > 100
$complexFilteredProducts = array_filter($products, function($product) {
return ($product['category'] === 'Electronics' || $product['category'] === 'Furniture')
&& $product['price'] > 100;
});
print_r($filteredProducts);
print_r($complexFilteredProducts);
How it works: The `array_filter` function, when combined with an anonymous function (closure) as its callback, offers a flexible way to filter arrays based on highly specific or multiple conditions. The callback receives each element of the array, and if it returns `true`, the element is included in the result; otherwise, it's excluded. This allows for complex logic, combining multiple criteria with logical operators (AND, OR) to precisely select the desired elements from a dataset.