PHP
Filtering an Array with Multiple Conditions
Master filtering PHP arrays using `array_filter` with a callback function to apply multiple custom criteria simultaneously for precise data selection.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'inStock' => true, 'category' => 'Electronics'],
['name' => 'Mouse', 'price' => 25, 'inStock' => false, 'category' => 'Electronics'],
['name' => 'Keyboard', 'price' => 75, 'inStock' => true, 'category' => 'Electronics'],
['name' => 'Desk Chair', 'price' => 150, 'inStock' => true, 'category' => 'Furniture'],
['name' => 'Monitor', 'price' => 300, 'inStock' => true, 'category' => 'Electronics']
];
// Filter for products that are 'inStock' AND 'category' is 'Electronics' AND 'price' is less than 500
$filteredProducts = array_filter($products, function($product) {
return $product['inStock'] === true &&
$product['category'] === 'Electronics' &&
$product['price'] < 500;
});
print_r($filteredProducts);
?>
How it works: This example demonstrates how to filter an array of associative arrays using `array_filter` with a callback function. The callback function receives each element of the array and returns `true` if the element should be included in the filtered result, or `false` otherwise. By combining multiple conditions with logical operators (like `&&` for AND, `||` for OR) inside the callback, you can perform complex, multi-criteria filtering operations.