Warning: Undefined array key "action" in /home/bakers/html/entryreply.php on line 5

Warning: Undefined variable $output in /home/bakers/html/entryreply.php on line 50

Warning: Undefined array key "EntrySubject" in /home/bakers/html/entryreply.php on line 51

Warning: Undefined variable $logintext in /home/bakers/html/entryreply.php on line 97

Warning: Undefined variable $reply_name in /home/bakers/html/entryreply.php on line 103

Warning: Undefined variable $reply_email in /home/bakers/html/entryreply.php on line 104
Perturb.org - interesting technology related things from around the internet

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;
    }
}


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 3.239.118.166
To prevent spam please submit by clicking the kitten: