PHP

Efficiently Filter PHP Arrays with Custom Callbacks

Learn how to use PHP's `array_filter` to easily remove elements from an array that don't meet specific criteria defined by a custom callback function.

<?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 to get only products that are in stock and price > $50
$available_expensive_products = array_filter($products, function($product) {
    return $product['in_stock'] && $product['price'] > 50;
});

print_r($available_expensive_products);

/*
Output:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Laptop
            [price] => 1200
            [in_stock] => 1
        )

    [2] => Array
        (
            [id] => 3
            [name] => Keyboard
            [price] => 75
            [in_stock] => 1
        )

)
*/
How it works: The `array_filter()` function iterates over each value in an array, passing it to the provided callback function. If the callback function returns `true`, the value is kept in the filtered array; otherwise, it is removed. This snippet demonstrates filtering an array of products, retaining only those that are marked as 'in_stock' and have a 'price' greater than 50, providing a flexible way to prune data based on complex conditions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs