Creating a dynamic multidimensional array

I am trying to create an array while parsing a string separated by dots

$string = "foo.bar.baz";
$value = 5

to

$arr['foo']['bar']['baz'] = 5;

I analyzed the keys using

$keys = explode(".",$string);

How can i do this?

+5
source share
3 answers

You can do:

$keys = explode(".",$string);
$last = array_pop($keys);

$array = array();
$current = &$array;

foreach($keys as $key) {
    $current[$key] = array();
    $current = &$current[$key];
}

$current[$last] = $value;

Demo

You can easily make a function if this is by passing a string and value as a parameter and returning an array.

+2
source

You can try the following solution:

function arrayByString($path, $value) {
  $keys   = array_reverse(explode(".",$path));

  foreach ( $keys as $key ) {
    $value = array($key => $value);
  }

  return $value;
}

$result = arrayByString("foo.bar.baz", 5);

/*
array(1) {
  ["foo"]=>
  array(1) {
    ["bar"]=>
    array(1) {
      ["baz"]=>
      int(5)
    }
  }
}
*/
+2
source

This has something to do with the question you can find the answer to here:

PHP One level deeper in the array, each loop created

You just need to change the code a bit:

$a = explode('.', "foo.bar.baz");
$b = array();
$c =& $b;

foreach ($a as $k) {
    $c[$k] = array();
    $c     =& $c[$k];
}

$c = 5;

print_r($b);
0
source

All Articles