phparraysmultidimensional-array

Declare a multidimensional array by using the values of a flat array as the keypath to a pre-defined value


I have array like this: $test = array(20, 30, 40);

And I want to set a multi-dimension array with using these values: $example[20][30][40] = 'string'

How can I do this?

Note: "20, 30, 40" just an example, my program will print some integers, and I want to set a multi-dimension array with these values and it can be more than 3 values.


Solution

  • You could do it that way:

    $example[$test[0]][$test[1]][$test[2]] = 'string'
    

    Or if the size of the array is variable you will need to do a recursive function to fill up your array.

    function fill_up($content, $value){
        $index = array_shift($content);
        if(count($content)){
            return array($index => fill_up($content, $value));
        } else {
            return array($index => $value);
        }
    }
    
    $example = array(20,30,40);
    $value = 'test';
    var_dump(fill_up($example, $value));