How can one create a multidimensional array in PHP with variable number of keys?

When creating a multidimensional array in PHP with a variable number of keys, you can use a loop to dynamically build the array structure. By iterating over an array of keys, you can nest arrays within each other based on the keys provided. This allows you to create a multidimensional array with a flexible number of dimensions.

$keys = ['key1', 'key2', 'key3']; // Array of keys
$value = 'example'; // Value to assign at the innermost level

$result = [];
$temp = &$result;

foreach ($keys as $key) {
    $temp[$key] = [];
    $temp = &$temp[$key];
}

$temp = $value; // Assign value at the innermost level

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