January 11th, 2013, 08:24 AM
Assigning values to associative array with dynamic keys
I have $options as an associative array with each value as mixed(can be strings, or other arrays). I won't have any objects there.
$keys is a numeric array & the number of keys is determined at runtime.
I want to have a result similar to this expression
$options[$keys][$keys].......[$keys[count($keys)-1]] = $value;
For example, if $keys = array('key1'), i want to do
$options['key1'] = $value;
& if $keys = array('key1', 'key2'), i want to do
$options['key1']['key2'] = $value; & so on
The problem with array_replace_recursive is that $value may itself be an array. Someway to constrain the depth to which array_replace_recursive can go? or maybe some other way?
January 11th, 2013, 09:26 AM
$keys = array('a', 'b');
$val = 123;
$curr = $val;
foreach (array_reverse($keys) as $key)
$curr = array($key => $curr);
var_dump( $curr );
January 14th, 2013, 01:26 AM
Thanks a lot