Thursday, 30 August 2018

PHP: with an associative array of counters, is it more idiomatic to explicitly set each value to 0 before the first increment?


I'm writing some code that builds up associative array of counters. When it encounters a new item for the first time it creates a new key and initializes it to zero. I.e.:


if (!array_key_exists($item, $counters)) {
    $counters[$item] = 0;
}
$counters[$item]++;

However, PHP actually does that first part implicitly. If I just do...
 $counters[$item]++;

... then $counters[$item] will evaluate to NULL and be converted to 0 before it's incremented. Obviously the second way is simpler and more concise, but it feels a little sleazy because it's not obvious that $counters[$item] might not exist yet. Is one way or the other preferred in PHP?
For comparison, in Python the idiomatic approach would be to use collections.Counter when you want keys that initialize themselves to 0, and a regular dictionary when you want to initialize them yourself. In PHP you only have the first option.

the first is preferred. the second option will generate a Notice in your logs that $counters[$item] is undefined. it still works but if you change display_errors = On; and error_reporting = E_ALL. in your php.ini file you will see these notices in your browser.

0 comments:

Post a Comment