[ create a new paste ] login | about

Link: http://codepad.org/VSDcjZ6i    [ raw code | output | fork ]

PHP, pasted on Sep 18:
<?php

$first = array("a", "b" => array("c", "d" => array("e", "f")), "g", "h" => array("f"));
$second = array("b", "d", "f");
$string = "foobar";

function assign(&$array, $keys, $value) {
    $last_key = array_pop($keys);
    $tmp = &$array;
    foreach($keys as $key) {
        if(!isset($tmp[$key]) || !is_array($tmp[$key])) {
            $tmp[$key] = array();
        }
        $tmp = &$tmp[$key];
    }
    $tmp[$last_key] = $value;
    unset($tmp);
}

assign($first, $second, $string);


print_r($first);


Output:
Array
(
    [0] => a
    [b] => Array
        (
            [0] => c
            [d] => Array
                (
                    [0] => e
                    [1] => f
                    [f] => foobar
                )

        )

    [1] => g
    [h] => Array
        (
            [0] => f
        )

)


Create a new paste based on this one


Comments: