PHP
Filter an Array of Objects by Property Value
Learn how to efficiently filter a PHP array containing objects based on a specific property's value, returning only matching objects.
<?php
class Product {
public $id;
public $name;
public $category;
public function __construct($id, $name, $category) {
$this->id = $id;
$this->name = $name;
$this->category = $category;
}
}
$products = [
new Product(1, 'Laptop', 'Electronics'),
new Product(2, 'Keyboard', 'Electronics'),
new Product(3, 'Desk Chair', 'Furniture'),
new Product(4, 'Mouse', 'Electronics'),
new Product(5, 'Bookshelf', 'Furniture'),
];
$filteredProducts = array_filter($products, function($product) {
return $product->category === 'Electronics';
});
// To re-index the array if desired:
$reIndexedProducts = array_values($filteredProducts);
print_r($reIndexedProducts);
?>
How it works: This snippet demonstrates filtering an array of objects based on a specific property's value. The `array_filter()` function iterates over each element, applying a callback function. If the callback returns `true`, the element is included in the new array; otherwise, it's excluded. The `array_values()` function is then used to reset the array keys, ensuring a numerically indexed array if desired.