PHP: Increment a hash variable in an E_NOTICE friendly way
I have a hash that contains counts for a bunch of stats. Unfortunately you can't just increment a hash like: $hash['key']++
and have it be E_NOTICE
compliant. If that key does not exist in the array and you try and increment it you will trigger an E_NOTICE
alert. I wrote this quick increment implementation that will allow you to increment a non-existing key.
$hash = [];
incr($hash['key']); // Inits to 1
incr($hash['key']); // Sets to 2
// Increment a variable (E_NOTICE compatible)
function incr(&$i, $value = 1) {
// If the value is already there add to it
if (isset($i)) {
$i += $value;
// If the value isn't there, just set it initially
} else {
$i = $value;
}
}