What are common pitfalls when accessing array elements in PHP, especially when dealing with nested arrays?

Common pitfalls when accessing array elements in PHP, especially with nested arrays, include not checking if the key exists before accessing it, not handling cases where the key may not exist, and not properly traversing through nested arrays. To avoid these pitfalls, always use isset() or array_key_exists() to check if a key exists before trying to access it, handle cases where the key may not exist gracefully, and use loops or recursive functions to navigate through nested arrays.

// Example of accessing nested array elements safely
$nestedArray = array(
    'key1' => 'value1',
    'key2' => array(
        'subkey1' => 'subvalue1',
        'subkey2' => 'subvalue2'
    )
);

// Check if the key exists before accessing it
if(isset($nestedArray['key2']['subkey1'])){
    $value = $nestedArray['key2']['subkey1'];
    echo $value; // Output: subvalue1
} else {
    echo "Key does not exist";
}