Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign to an arbitrarily deep array index?

Tags:

arrays

php

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

For example:

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

Now, $some_array should equal

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

At the moment, I am 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?

like image 421
Austin Hyde Avatar asked Jun 20 '11 18:06

Austin Hyde


People also ask

How to create array with of particular length in JavaScript?

One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert. equal(arr. length, LEN); // arr only has holes in it assert.

Can you nest arrays in Java?

Two dimensional arrays are useful for storing matrices for example. In Java, arrays of more than one dimension are created by making arrays of arrays. This is known as nesting.

How do you find the object property by key deep in a nested JavaScript array?

To use: let result = deepSearchByKey(arrayOrObject, 'key', 'value'); This will return the object containing the matching key and value.


2 Answers

Recursive solution (not tested):

 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);
      }
    }
like image 125
molnarm Avatar answered Sep 28 '22 04:09

molnarm


Wow, reminds me of Lisp.

Yea, eval is generally not the best idea.

Personally, I would simply iterate:

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

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

If you're in PHP 5 you can probably get rd of some of those '&' too

like image 20
cwallenpoole Avatar answered Sep 28 '22 06:09

cwallenpoole