0

I have a :

$value = "val";

I also have an array :

$keys = ['key1', 'key2', 'key3'...]

The keys in that array are dynamically generated, and can go from 2 to 10 or more entries.

My goal is getting this :

$array['key1']['key2']['key3']... = $value;

How can I do that ?

Thanks

2 Answers 2

6

The easiest, and least messy way (ie not using references) would be to use a recursive function:

function addArrayLevels(array $keys, array $target)
{
      if ($keys) {
          $key = array_shift($keys);
          $target[$key] = addArrayLevels($keys, []);
      }
      return $target;
}

//usage
$keys = range(1, 10);
$subArrays = addARrayLevels($keys, []);

It works as you can see here.

How it works is really quite simple:

  • if ($keys) {: if there's a key left to be added
  • $key = array_shift($keys); shift the first element from the array
  • $target[$key] = addArrayLevels($keys, []);: add the index to $target, and call the same function again with $keys (after having removed the first value). These recursive calls will go on until $keys is empty, and the function simply returns an empty array

The downsides:

  • Recursion can be tricky to get your head round at first, especially in complex functions, in code you didn't write, but document it well and you should be fine

The pro's:

  • It's more flexible (you can use $target as a sort of default/final assignment variable, with little effort (will add example below if I find the time)
  • No reference mess and risks to deal with

Example using adaptation of the function above to assign value at "lowest" level:

function addArrayLevels(array $keys, $value)
{
      $return = [];
      $key = array_shift($keys);
      if ($keys) {
          $return[$key] = addArrayLevels($keys, $value);
      } else {
          $return[$key] = $value;
      }
      return $return;
}

$keys = range(1, 10);
$subArrays = addARrayLevels($keys, 'innerValue');
var_dump($subArrays);

Demo

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

Comments

5

I don't think that there is built-in function for that but you can do that with simple foreach and references.

$newArray = [];
$keys = ['key1', 'key2', 'key3'];
$reference =& $newArray;

foreach ($keys as $key) {
    $reference[$key] = [];

    $reference =& $reference[$key];
}

unset($reference);

var_dump($newArray);

1 Comment

@JeremyBelolo: Please read the linked answer in my "pro's" list for an explanation, but believe me when I say: avoid references when you can, and you really can avoid them here

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.