In PHP, how do I deduplicate objects with built-in functions?

In PHP, you can deduplicate objects using built-in functions such as `array_unique` and custom approaches. Below is an example of how to achieve this by converting the objects to an array and then back to objects after removing duplicates.

<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $people = [ new Person('Alice', 30), new Person('Bob', 25), new Person('Alice', 30), // Duplicate new Person('Charlie', 35) ]; // Function to deduplicate objects function deduplicate($people) { $unique_people = []; foreach ($people as $person) { $unique_key = serialize($person); // Serialize object for unique comparison if (!in_array($unique_key, $unique_people)) { $unique_people[] = $unique_key; } } return array_map('unserialize', $unique_people); // Unserialize back to objects } $deduplicated_people = deduplicate($people); print_r($deduplicated_people); ?>

PHP deduplicate objects array_unique remove duplicates serialize unserialize