Skip to content
Advertisement

How to dynamically add elements to the array value of an SplObjectStorage object

Suppose we have an Index class:

JavaScript

So far so good? ok.

Now, imagine we have to implement a dictionary that maps words to their synonyms.

JavaScript

This outputs:

JavaScript

If wanna add one more synonym to our word, how to go about that? I tried this:

JavaScript

This, however, outputs the same output as the one above :

JavaScript

What am I missing? ????

Advertisement

Answer

Save all synonyms as array instead of single string:

JavaScript

So now you can add new item $synonymsDictionary[$word][] = 'unlucky'


Also offsetGet only returns data, not reference to data. So what you later change is never assigned back to synonyms dictionary.

So you need this:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement