PHP: with an associative array of counters, is it more idiomatic to explicitly initialize each value to 0 before the first increment? -
i'm writing code builds associative array of counters. when encounters new item first time creates new key , initializes zero. i.e.:
if (!array_key_exists($item, $counters)) { $counters[$item] = 0; } $counters[$item]++; however, php first part implicitly. if do...
$counters[$item]++; ... $counters[$item] evaluate null , converted 0 before it's incremented. second way simpler , more concise, feels little sleazy because it's not obvious $counters[$item] might not exist yet. 1 way or other preferred in php?
for comparison, in python idiomatic approach use collections.counter when want keys initialize 0, , regular dictionary when want initialize them yourself. in php have first option.
the first preferred. second option generate notice in logs $counters[$item] undefined. still works if change display_errors = on; , error_reporting = e_all. in php.ini file see these notices in browser.
Comments
Post a Comment