Assign arbitrarily deep array index?

If I have an array that matches successively recursive keys in another array, what is the best way to assign a value to this "path" (if you want to name it)?

For instance:

$some_array = array();
$path = array('a','b','c');
set_value($some_array,$path,'some value');

Now $some_arraymust equal

array(
  'a' => array(
    'b' => array(
      'c' => 'some value'
)))

I am currently using the following:

function set_value(&$dest,$path,$value) {
  $addr = "\$dest['" . implode("']['", $path) . "']";
  eval("$addr = \$value;");
}

Obviously, this is a very naive approach and poses a security risk, so how would you do it?

+5
source share
4 answers

Recursive solution (not verified):

 function set_value(&$dest,$path,$value) {
      $index=array_shift($path);
      if(empty($path)){
        // on last level
        $dest[$index]=$value;
      }
      else{
        // descending to next level
        set_value($dest[$index],$path,$value);
      }
    }
+2
source

Wow, Lisp reminds me.

Yes, evalusually not the best idea.

Personally, I would just try:

function set_value(&$dest,$path,$value) {
  $val =& $dest;
  for($i = 0; $i > count($path) - 1; $i++) {
     $val =& $val[$i];
  }

  $val[$path[$i]] = $value;
}

PHP 5, , , "&"

+2
function set_value(&$dest, $path, $value)
{
  # allow for string paths of a/b/c
  if (!is_array($path)) $path = explode('/', $path);

  $a = &$dest;
  foreach ($path as $p)
  {
    if (!is_array($a)) $a = array();
    $a = &$a[$p];
  }

  return $a = $value;
}


set_value($a, 'a/b/c', 'foo');

Updated to work with keys that do not yet exist, and accept either an array or a string path.

+2
source
function set_value(&$dest, $path, $value) {
    $dest = array(array_pop($path) => $value);
    for($i = count($path) - 1; $i >= 0; $i--) {
        $dest = array($path[$i] => $dest);
    }
}
+2
source

All Articles