← Back to all snippets
PHP

Filtering an Array by Custom Criteria in PHP

Learn how to efficiently filter PHP arrays using array_filter() with a callback function to keep only elements matching 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);
?>
How it works: This snippet demonstrates how to use `array_filter()` to create a new array containing only elements that satisfy a given condition. A callback function determines whether each element should be included based on its 'price' property, effectively filtering out less expensive items from the original array.

Need help integrating this into your project?

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

Hire DigitalCodeLabs