PHP
Filtering an Array by Custom Criteria in PHP
Learn how to efficiently filter PHP arrays using array_filter() with a callback function to keep only elements matching specific conditions.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'price' => 75],
['id' => 4, 'name' => 'Monitor', 'price' => 300],
];
$expensiveProducts = array_filter($products, function($product) {
return $product['price'] > 100;
});
print_r($expensiveProducts);
?>
How it works: This snippet demonstrates how to use `array_filter()` to create a new array containing only elements that satisfy a given condition. A callback function determines whether each element should be included based on its 'price' property, effectively filtering out less expensive items from the original array.