PHP
Filter PHP Array Elements by a Custom Condition
Learn to selectively remove or keep elements in a PHP array based on a user-defined callback function, useful for data validation, cleaning, or specific selections.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 1200, 'in_stock' => true],
['id' => 2, 'name' => 'Mouse', 'price' => 25, 'in_stock' => false],
['id' => 3, 'name' => 'Keyboard', 'price' => 75, 'in_stock' => true],
['id' => 4, 'name' => 'Monitor', 'price' => 300, 'in_stock' => false]
];
// Filter products that are in stock and cost less than $100
$affordableInStockProducts = array_filter($products, function($product) {
return $product['in_stock'] && $product['price'] < 100;
});
print_r($affordableInStockProducts);
// Filter out empty strings from a simple array
$data = ['apple', '', 'banana', null, 'orange', false, 'grape'];
$filteredData = array_filter($data);
print_r($filteredData);
?>
How it works: The `array_filter` function allows you to filter elements of an array using a callback function. The first example uses an anonymous function to filter a list of products, keeping only those that are 'in_stock' and have a 'price' less than $100. The callback should return `true` to keep the element and `false` to remove it. If no callback is provided (second example), `array_filter` removes all elements that evaluate to `false` in a boolean context (e.g., `false`, `null`, `0`, `''`, `[]`).