How to create a dynamic array key path?

I have a string var that get’s built with a string something like:

$selection = "[selection1][selection2]";

selection1 and selection2 can really be any word. And there can be more selections in the var such as “[selection1][selection2][selection3][selection4]”

Is there anyway to use this to define a dynamic array key path so it can be used to assign values to an array? Something like:

$dynamic_selection . $selection = "red";

Which would eval into an array key path like:

$dynamic_selection[ 'selection1' ][ 'selection2' ] = "red";

Hi @NormsIM,

Could you please tell us about the real problem you are trying to solve with this code. What is the high level overview of what you have going on?

I’m not sure, but this sounds like a need for variable variables

i.e. values are assigned to array members that have dynamic keys

$some_arr[{$$dynamic_rando}] = $val; 

I never feel 100% at ease with variable variables, check syntax and test if you go this way.

1) Extract elements (preg_match_all).
2) You now know how many layers deep you're going, and the keys for each level.
3.a) $target = 'some_arr';
3) Foreach key in the array of keys:
4) If ${$target}[$key] Does Not Exist, ${$target}[$key] = array();
5) $target += "['".$key."']";
6) EndForeach

(Above is untested, but I… think it works.)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.