What are some best practices for recursively traversing objects in PHP to access and display their elements?

When recursively traversing objects in PHP to access and display their elements, it is important to implement a function that can handle nested objects and arrays. One common approach is to use a recursive function that checks if the current element is an array or an object, and if so, recursively call itself to traverse the nested elements. This allows for a flexible and scalable solution to access and display elements within complex nested structures.

function displayElements($obj) {
    if (is_array($obj) || is_object($obj)) {
        foreach ($obj as $key => $value) {
            echo $key . ': ';
            displayElements($value);
        }
    } else {
        echo $obj . PHP_EOL;
    }
}

// Example usage
$data = [
    'name' => 'John',
    'age' => 30,
    'address' => [
        'street' => '123 Main St',
        'city' => 'New York'
    ]
];

displayElements($data);