How can you check if a specific element exists in an array of objects in PHP?

To check if a specific element exists in an array of objects in PHP, you can loop through each object in the array and compare the desired element with the element in each object. If a match is found, you can return true; otherwise, return false.

function checkElementExists($array, $element) {
    foreach ($array as $obj) {
        if (isset($obj->$element)) {
            return true;
        }
    }
    return false;
}

// Example usage
$objects = [
    (object)['name' => 'Alice', 'age' => 25],
    (object)['name' => 'Bob', 'age' => 30],
    (object)['name' => 'Charlie', 'age' => 35]
];

if (checkElementExists($objects, 'name')) {
    echo 'Element "name" exists in the array of objects.';
} else {
    echo 'Element "name" does not exist in the array of objects.';
}