PHP
Filter an Array by Multiple Conditions
Discover how to filter an array of objects or associative arrays in PHP based on multiple custom criteria using the flexible `array_filter()` function with a callback.
<?php
$products = [
['name' => 'Laptop Pro', 'category' => 'Electronics', 'price' => 1500, 'in_stock' => true],
['name' => 'Gaming Mouse', 'category' => 'Electronics', 'price' => 75, 'in_stock' => true],
['name' => 'Office Chair', 'category' => 'Furniture', 'price' => 350, 'in_stock' => false],
['name' => 'External HDD', 'category' => 'Electronics', 'price' => 120, 'in_stock' => true],
['name' => 'Dining Table', 'category' => 'Furniture', 'price' => 600, 'in_stock' => true]
];
// Filter products that are 'Electronics', have a 'price' less than 200, AND are 'in_stock'
$filteredProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics'
&& $product['price'] < 200
&& $product['in_stock'] === true;
});
print_r(array_values($filteredProducts)); // array_values() re-indexes the array
/* Output:
Array
(
[0] => Array
(
[name] => Gaming Mouse
[category] => Electronics
[price] => 75
[in_stock] => 1
)
[1] => Array
(
[name] => External HDD
[category] => Electronics
[price] => 120
[in_stock] => 1
)
)
*/
How it works: The `array_filter()` function is perfect for selecting elements from an array that meet specific conditions. By passing an anonymous function (callback) as the second argument, you can define complex logic. The callback receives each array element, and if it returns `true`, the element is included in the result; otherwise, it's excluded. This example filters products that are electronic, under $200, and currently in stock. `array_values()` is used to re-index the filtered array from 0 after elements have been removed.