In PHP, how do I search objects for beginners?

In this tutorial, we will learn how to search through objects in PHP. This is an essential skill for any beginner looking to manipulate data structures effectively.

PHP, objects, search, beginner tutorial, data structures


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 searchByName($people, $name) {
    foreach ($people as $person) {
        if ($person->name === $name) {
            return $person;
        }
    }
    return null; // Return null if not found
}

// Example usage
$searchName = "Bob";
$result = searchByName($people, $searchName);

if ($result) {
    echo "Found: " . $result->name . ", Age: " . $result->age;
} else {
    echo "Person not found.";
}
?>
    

PHP objects search beginner tutorial data structures