PHP
Filter Array Elements Based on a Callback
Learn how to filter elements from a PHP array using a custom callback function with `array_filter`, effectively selecting items that meet specific criteria.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
['name' => 'T-Shirt', 'price' => 20, 'category' => 'Apparel'],
];
// Filter products with a price greater than 50
$expensiveProducts = array_filter($products, function($product) {
return $product['price'] > 50;
});
echo json_encode(array_values($expensiveProducts), JSON_PRETTY_PRINT);
// Output:
// [
// {
// "name": "Laptop",
// "price": 1200,
// "category": "Electronics"
// },
// {
// "name": "Keyboard",
// "price": 75,
// "category": "Electronics"
// }
// ]
?>
How it works: This snippet demonstrates `array_filter()` to create a new array containing only elements that satisfy a specific condition. It takes an array and a callback function as arguments. The callback function is executed for each element, and if it returns `true`, the element is included in the resulting array. `array_values()` is used to re-index the filtered array.