PHP
Filter Array Elements Using Multiple Conditions
Efficiently filter array elements in PHP based on complex criteria using a custom callback function with `array_filter`, applying multiple conditions simultaneously.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'name' => 'Desk Chair', 'category' => 'Furniture', 'price' => 250, 'in_stock' => false],
['id' => 3, 'name' => 'Smartphone', 'category' => 'Electronics', 'price' => 800, 'in_stock' => true],
['id' => 4, 'name' => 'Bookcase', 'category' => 'Furniture', 'price' => 150, 'in_stock' => true],
['id' => 5, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75, 'in_stock' => true],
['id' => 6, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300, 'in_stock' => false],
];
// Filter for products that are 'Electronics', 'in_stock', and cost more than $100
$filteredProducts = array_filter($products, function($product) {
return $product['category'] === 'Electronics' &&
$product['in_stock'] === true &&
$product['price'] > 100;
});
/*
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Laptop
[category] => Electronics
[price] => 1200
[in_stock] => 1
)
[1] => Array
(
[id] => 3
[name] => Smartphone
[category] => Electronics
[price] => 800
[in_stock] => 1
)
)
*/
print_r($filteredProducts);
// Example with external variables (PHP 7.4+ for arrow functions, or use `use` keyword)
$minPrice = 200;
$requiredCategory = 'Furniture';
$filteredByExternalVars = array_filter($products, function($product) use ($minPrice, $requiredCategory) {
return $product['category'] === $requiredCategory &&
$product['price'] >= $minPrice;
});
/*
Output:
Array
(
[0] => Array
(
[id] => 2
[name] => Desk Chair
[category] => Furniture
[price] => 250
[in_stock] =>
)
)
*/
print_r($filteredByExternalVars);
?>
How it works: The `array_filter()` function processes each element of an array, passing it to a user-defined callback function. If the callback returns `true`, the element is included in the new filtered array; otherwise, it's excluded. This snippet demonstrates how to apply multiple conditions within the callback using logical operators (`&&`, `||`) to perform powerful and flexible filtering on arrays of associative arrays, such as filtering a list of products by category, price, and stock status. It also shows how to pass external variables into the callback using the `use` keyword.