PHP

Filter Array Elements with a Custom Callback Function (`array_filter`)

Efficiently remove unwanted elements from a PHP array using `array_filter` and a user-defined callback function based on 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);
/*
Expected Output:
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Laptop
            [price] => 1200
        )

    [3] => Array
        (
            [id] => 4
            [name] => Monitor
            [price] => 300
        )

)
*/
How it works: `array_filter()` iterates over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the current value from the input array is included in the result array. This snippet demonstrates how to filter an array of products, keeping only those with a price greater than 100, effectively creating a subset of the original array based on custom logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs