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

Given the above code, how can I set a value in $first at the indexes defined in $second to the contents of $string? Meaning, for this example, it should be $first["b"]["d"]["f"] = $string;, but the contents of $second and $first can be of any length. $second will always be one dimensional however. Here's what I had tried, which didn't seem to work as planned:

$key = "";
$ptr = $first;
for($i = 0; $i < count($second); $i++)
{
    $ptr &= $ptr[$second[$i]];
    $key = key($ptr);
}
$first[$key] = $string;

This will do $first["f"] = $string; instead of the proper multidimensional indexes. I had thought that using key would find the location within the array including the levels it had already moved down.

How can I access the proper keys dynamically? I could manage this if the number of dimensions were static.

EDIT: Also, I'd like a way to do this which does not use eval.

1 Answer 1

9

It's a bit more complicated than that. You have to initialize every level if it does not exist yet. But your actual problems are:

  • The array you want to add the value to is in $ptr, not in $first.
  • $x &= $y is shorthand for $x = $x & $y (bitwise AND). What you want is x = &$y (assign by reference).

This should do it:

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);
}

Usage:

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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.