Dynamically creating/inserting into an associative array in PHP

Posted by emil.mp on Stack Overflow See other posts from Stack Overflow or by emil.mp
Published on 2010-03-15T13:24:44Z Indexed on 2010/03/15 13:29 UTC
Read the original article Hit count: 185

Filed under:
|
|

I'm trying to build an associative array in PHP dynamically, and not quite getting my strategy right. Basically, I want to insert a value at a certain depth in the array structure, for instance:

$array['first']['second']['third'] = $val;

Now, the thing is, I'm not sure if that depth is available, and if it isn't, I want to create the keys (and arrays) for each level, and finally insert the value at the correct level.

Since I'm doing this quite a lot in my code, I grew tired of doing a whole bunch of "array_key_exists", so I wanted to do a function that builds the array for me, given a list of the level keys. Any help on a good strategy for this is appreciated. I'm sure there is a pretty simple way, I'm just not getting it...

© Stack Overflow or respective owner

Related posts about php

Related posts about associative-array