PHP
Filter PHP Array with Multiple Conditions
Learn to precisely filter an array using `array_filter` combined with a callback function that evaluates multiple criteria, returning only matching elements.
<?php
$products = [
['name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200, 'inStock' => true],
['name' => 'Mouse', 'category' => 'Electronics', 'price' => 25, 'inStock' => false],
['name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75, 'inStock' => true],
['name' => 'Book', 'category' => 'Literature', 'price' => 30, 'inStock' => true],
['name' => 'Monitor', 'category' => 'Electronics', 'price' => 300, 'inStock' => true],
['name' => 'Pen', 'category' => 'Stationery', 'price' => 5, 'inStock' => false],
];
// Filter for electronic products that are in stock and cost less than $500
$filteredProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics' &&
$product['inStock'] === true &&
$product['price'] < 500;
});
echo "Filtered Products:
";
print_r($filteredProducts);
/* Expected output:
Array
(
[2] => Array
(
[name] => Keyboard
[category] => Electronics
[price] => 75
[inStock] => 1
)
[4] => Array
(
[name] => Monitor
[category] => Electronics
[price] => 300
[inStock] => 1
)
)
*/
// Another example: Products over $100 OR out of stock
$expensiveOrOutOfStock = array_filter($products, function($product) {
return $product['price'] > 100 || !$product['inStock'];
});
echo "
Expensive or Out of Stock Products:
";
print_r($expensiveOrOutOfStock);
?>
How it works: This snippet demonstrates using `array_filter` to filter an array of associative arrays based on multiple conditions. The `array_filter` function takes the array and a callback function. This callback is executed for each element, and only elements for which the callback returns `true` are included in the resulting array. The examples show combining multiple logical conditions (`&&` for AND, `||` for OR) within the callback to achieve precise filtering, useful for various data selection needs.