What are the best practices for accessing nested values in a JSON object using PHP?

When working with nested JSON objects in PHP, it's important to access the values correctly to avoid errors. One common method is to use the arrow notation (->) to access nested objects and arrays within the JSON structure. By using this notation and checking for the existence of keys at each level, you can safely access nested values in a JSON object.

// Sample JSON object
$json = '{
    "user": {
        "name": "John Doe",
        "address": {
            "street": "123 Main St",
            "city": "New York"
        }
    }
}';

// Decode the JSON object
$data = json_decode($json);

// Access nested values
if(isset($data->user->name)) {
    $name = $data->user->name;
    echo "User's name: " . $name . PHP_EOL;
}

if(isset($data->user->address->city)) {
    $city = $data->user->address->city;
    echo "User's city: " . $city . PHP_EOL;
}