What are some best practices for assigning values to multidimensional arrays in PHP to avoid unexpected behavior?

When assigning values to multidimensional arrays in PHP, it is important to ensure that the keys exist before attempting to assign a value to them. This helps avoid unexpected behavior such as errors or overwriting existing values. One way to achieve this is by using conditional checks to create nested arrays if the keys do not exist.

// Example of assigning values to a multidimensional array safely
$multiArray = [];

// Check if the first level key exists, if not, create it
if (!isset($multiArray['first_level'])) {
    $multiArray['first_level'] = [];
}

// Check if the second level key exists, if not, create it
if (!isset($multiArray['first_level']['second_level'])) {
    $multiArray['first_level']['second_level'] = [];
}

// Assign a value to the second level key
$multiArray['first_level']['second_level']['value'] = 'Hello, World!';

// Output the multidimensional array
print_r($multiArray);