In PHP, how do I search objects in vanilla PHP?

keywords: PHP search objects, PHP object example, object property search
description: Learn how to search for objects by properties in PHP with this practical example.
<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Create an array of Person objects $people = [ new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) ]; // Function to search for a person by name function searchPersonByName($people, $searchName) { foreach ($people as $person) { if ($person->name === $searchName) { return $person; } } return null; // Return null if not found } // Example usage $searchResult = searchPersonByName($people, "Bob"); if ($searchResult) { echo "Found: " . $searchResult->name . ", Age: " . $searchResult->age; } else { echo "Person not found."; } ?>

keywords: PHP search objects PHP object example object property search