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
Related Questions
- What are the limitations of using the INT and float data types for decimal numbers in PHP?
- How can PHP be used to dynamically adjust the number of entries displayed on a page based on the length of user input?
- What are the best practices for handling variable values in PHP when saving to a database?