Search code examples
phparraysmultidimensional-arraydynamically-generatedkeypaths

Dynamically create a multidimensional array from an array of keypath values and a terminating value


What is the easiest way to create multi-dimensional array in php dynamically?

Here a static version:

$tab['k1']['k2']['k3'] = 'value';

I would like to avoid eval().
I'm not successful with variable variable ($$)
so I'm trying to develop a function fun with such a signature:

$tab = fun($tab, array('k1', 'k2', 'k3'), 'value');

Solution

  • There are a number of ways to achieve this, but here is one which uses PHP's ability to have N arguments passed to a function. This gives you the flexibility of creating an array with a depth of 3, or 2, or 7 or whatever.

    // pass $value as first param -- params 2 - N define the multi array
    function MakeMultiArray()
    {
        $args = func_get_args();
        $output = array();
        if (count($args) == 1)
            $output[] = $args[0]; // just the value
        else if (count($args) > 1)
        {
            $output = $args[0];
            // loop the args from the end to the front to make the array
            for ($i = count($args)-1; $i >= 1; $i--)
            {
                $output = array($args[$i] => $output);
            }
        }
        return $output;
    }   
    

    Here's how it would work:

    $array = MakeMultiArray('value', 'k1', 'k2', 'k3');
    

    And will produce this:

    Array
    (
        [k1] => Array
            (
                [k2] => Array
                    (
                        [k3] => value
                    )
            )
    )