-6

I have the following array of keys:

$keys = $array('one', 'two', 'three');

and this value:

$value = 'text';

and I would like to create a new array:

$array['one']['two']['three'] = 'text';

How can I accomplish this?

1
  • You want the array to be your keys? Commented Sep 11, 2015 at 11:41

1 Answer 1

1
$array = array();
$current =& $array;
$keys = $array('one', 'two', 'three');
$value = 'text';

foreach (array_slice($keys, 0, -1) as $k) {
    $current[$k] = array();
    $current = & $current[$k];
}
$current[$keys[count($keys)-1]] = $value;

Using a reference for $current allows it modify the nested arrays in place.

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

1 Comment

it doesn't work for me i have an error message : Fatal error: Function name must be a string on line 4 ! line targeted $keys = $array('one', 'two', 'three');

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.