What are the best practices for accessing nested arrays in PHP to avoid errors like undefined indexes or invalid arguments in foreach loops?

When accessing nested arrays in PHP, it's important to check if the keys or indexes exist before attempting to access them to avoid errors like undefined indexes or invalid arguments in foreach loops. One way to do this is by using functions like isset() or array_key_exists() to verify the existence of the keys before accessing them.

// Example of accessing nested arrays safely
$array = [
    'key1' => [
        'subkey1' => 'value1',
        'subkey2' => 'value2'
    ],
    'key2' => [
        'subkey3' => 'value3'
    ]
];

if (isset($array['key1']) && is_array($array['key1'])) {
    foreach ($array['key1'] as $subkey => $value) {
        echo $subkey . ': ' . $value . "\n";
    }
}