PHP
Filtering Arrays by Custom Conditions
Learn how to filter elements from a PHP array using array_filter() and a custom callback function to match specific criteria efficiently.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'in_stock' => true],
['name' => 'Mouse', 'price' => 25, 'in_stock' => false],
['name' => 'Keyboard', 'price' => 75, 'in_stock' => true],
['name' => 'Monitor', 'price' => 300, 'in_stock' => true],
['name' => 'Webcam', 'price' => 50, 'in_stock' => false],
];
$inStockProducts = array_filter($products, function($product) {
return $product['in_stock'] === true && $product['price'] < 500;
});
print_r($inStockProducts);
?>
How it works: This snippet demonstrates how to filter an array of associative arrays based on multiple custom conditions using `array_filter()`. It iterates through each element and applies an anonymous function as a callback. Only elements for which the callback returns `true` are included in the resulting filtered array, effectively retrieving products that are in stock and under a certain price.