1

I'm trying to figure out how I would do this, basically I want the function to add to the following array:

$this->array['key1']['key2']['key3'] = 'value'

From a single dimensional array like $this->keys:

Array
(
    [0] => key1
    [1] => key2
    [2] => key3
)

My function would be:

function addToArray($value) {
 $this->array = ...
}

I have had a few ideas of using foreach $this->keys or for but I don't know how I would preserve the existing array while adding new values onto it.

$keys is maintained in a separate function

For example:

foreach ($this->keys as $key) {
  $array = $this->array[$key]
}
$array = $value;

But this would create a new single dimensional array and not add to the multidimensional $this->array. Maybe I am just not thinking correctly.

6
  • 2
    Something like this: 3v4l.org/DpQMq
    – Passerby
    Commented Dec 5, 2013 at 5:47
  • @Passerby I see you beat me to it. Post yours as an answer and I'll take mine down.
    – Grexis
    Commented Dec 5, 2013 at 5:53
  • Thank you both, unfortunately, it doesn't work if the array exists with other values. For example, adding a $this->array['key1'] = 'value1'; before the function breaks it. Error: Cannot create references to/from string offsets nor overloaded objects Commented Dec 5, 2013 at 5:57
  • Well, that's not exactly a multidimensional array is it...
    – Grexis
    Commented Dec 5, 2013 at 5:59
  • Lol, yes, I guess you're right. Guess it is time for bed for me, obviously I'm not thinking correctly. Thank you for the code though, it does work now that I'm using it correctly. Commented Dec 5, 2013 at 6:06

1 Answer 1

2

Try something like the following:

function addToArray($value){
    $tempArray = &$this->array;
    foreach($this->keys as $key){
        $tempArray = &$tempArray[$key];
    }
    $tempArray = $value;
}

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.