5

I'm trying to create an array while parsing a string separated with dots

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

to

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

I parsed the keys with

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

How could I do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Paté
  • 1,914
  • 2
  • 22
  • 33

3 Answers3

2

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 out if this, passing the string and the value as parameter and returning the array.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @dev: Because an array is copied when you assign it to a variable. If you'd not use references, it would not work. – Felix Kling Nov 03 '11 at 10:59
2

You can try 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)
    }
  }
}
*/
hsz
  • 148,279
  • 62
  • 259
  • 315
0

This is somehow related to the question you can find an answer to, here:

PHP One level deeper in array each loop made

You would just have to change the code a little 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);
Community
  • 1
  • 1
aurora
  • 9,607
  • 7
  • 36
  • 54