← Back to all snippets
PHP

Filter Array of Associative Arrays by Key Value

Learn how to efficiently filter an array of associative arrays in PHP, retaining only elements where a specific key matches a desired value.

<?php
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['id' => 3, 'name' => 'Mouse', 'category' => 'Peripherals', 'price' => 25],
    ['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300],
];

$electronicsProducts = array_filter($products, function($product) {
    return $product['category'] === 'Electronics';
});

print_r($electronicsProducts);
?>
How it works: This snippet demonstrates using `array_filter()` with a callback function to filter an array of associative arrays. The callback receives each element and should return `true` to keep the element or `false` to discard it. In this example, it filters `products` to only include those where the `category` key's value is 'Electronics'.

Need help integrating this into your project?

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

Hire DigitalCodeLabs