2

my function:

function setItem(array $arr, $item, $value, $delimiter = '.') {
    $nodes = explode($delimiter, $item);
    $code = "\$arr['".join("']['", $nodes)."'] = \$value;";
    eval($code);
    return $arr;
}

using:

$data = array();
$data = setItem($data, 'test.qwerty.sub', 'value');

Is there way without "eval"?

2 Answers 2

3

Yes, but it involves using references:

function setItem(array &$arr, $path, $value, $delim = '.'){

  $path = explode($delim, $path);

  $root = &$arr;

  // pointer to the current item      
  $current = &$arr;

  foreach($path as $item){
    $current[$item] = array();

    // set pointer to the newly created array
    $current = &$current[$item];
  }

  // reached the last path component;
  // assign the value to it
  $current = $value;

  return $root;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it with recursion:

function setItem($item, $value, $delimiter = '.') {
    $nodes = explode($delimiter, $item, 2);
    if(!isset($nodes[1]))
        $data = $value;
    else
        $data = setItem($nodes[1], $value, $delimiter);
    return array($nodes[0] => $data);
}

$data = setItem('test.qwerty.sub', 'value');

Comments

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.