← Back to all snippets
PHP

Filtering PHP Arrays with Custom Conditions

Learn how to efficiently filter elements from a PHP array using a user-defined callback function with `array_filter`, enabling powerful data manipulation based on custom logic.

<?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'],
    ['name' => 'Jeans', 'price' => 60, 'category' => 'Apparel'],
];

// Filter products with price less than $100
$cheapProducts = array_filter($products, function ($product) {
    return $product['price'] < 100;
});

echo json_encode($cheapProducts, JSON_PRETTY_PRINT);
/*
Expected output:
[
    {
        "name": "Mouse",
        "price": 25,
        "category": "Electronics"
    },
    {
        "name": "Keyboard",
        "price": 75,
        "category": "Electronics"
    },
    {
        "name": "T-Shirt",
        "price": 20,
        "category": "Apparel"
    },
    {
        "name": "Jeans",
        "price": 60,
        "category": "Apparel"
    }
]
*/
?>
How it works: The `array_filter()` function iterates over each value in an array, passing it to a user-defined callback function. If the callback function returns `true`, the value is included in the new filtered array; otherwise, it's excluded. This snippet demonstrates filtering an array of products to include only those with a price under 100.

Need help integrating this into your project?

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

Hire DigitalCodeLabs