What are some common pitfalls when trying to access objects and arrays in PHP?

One common pitfall when trying to access objects and arrays in PHP is not checking if the key or property exists before trying to access it. This can lead to errors if the key or property does not exist. To avoid this, you should always use isset() or property_exists() to check if the key or property exists before accessing it.

// Check if the key exists in an array before accessing it
$array = ['key' => 'value'];
if (isset($array['key'])) {
    $value = $array['key'];
    echo $value;
}

// Check if the property exists in an object before accessing it
class MyClass {
    public $property = 'value';
}

$obj = new MyClass();
if (property_exists($obj, 'property')) {
    $value = $obj->property;
    echo $value;
}