On Thu, Sep 12, 2019 at 4:11 PM Rowan Tommins <rowan.coll...@gmail.com> wrote:
> On Thu, 12 Sep 2019 at 14:55, Claude Pache <claude.pa...@gmail.com> wrote: > > > Le 12 sept. 2019 à 15:33, Marco Pivetta <ocram...@gmail.com> a écrit : > > > > $foo[$key1][$key2] = ($foo[$key1][$key2] ?? 0) + 1; > > > > Marco Pivetta > > > > > > That violates blatantly DRY (twice the exact same lengthy expression > > `$foo[$key1][$key2]`), so it is not a satisfactory solution. > > > > > Agreed; it's certainly neater than all the isset() checks, but it's > definitely a bit ugly. > > To clarify my point, the reason why people write this: > > $foo[$key1][$key2]++; > > Is not because they're lazy, it's because *it expresses their intent*. > > The ?key syntax was one suggestion for how to express the intent safely in > that particular scenario. Another way might be that the array is > initialised a different way; completely off the top of my head, something > like this: > > $foo = new Dictionary<string, Dictionary<string, int=0>>; > > That could express the intent of "this variable is going to be used as an > accumulator with these dimensions". > > The "if isset" lines, in my opinion, don't express any intent, and they > don't protect against any real errors; they're just noise to work around a > short-coming in the language. FTR this is basically what Python does via defaultdict: https://docs.python.org/3/library/collections.html#collections.defaultdict I think it is the "cleanest" solution to this problem overall. Though it does need a separate structure, rather than our favorite PHP array. Nikita