Search code examples
phparraysincrementnull-coalescing

Best practice: how to increment not existing element of array


I want to increment a value of an array, which is potentially not existing yet.

$array = [];
$array['nonExistentYet']++; // Notice

Problem

This leads to a NOTICE.

Attempt

I found a way to do this, but its kinda clunky:

$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;

Question

Is there a more human readable/elegant way to do this?


Solution

  • My standard implementation for this is:

    if (isset($array['nonExistentYet']))
       $array['nonExistentYet']++;
    else
       $array['nonExistentYet'] = 1;
    

    But this is one of the rarely scenarios where I use the @ operator to suppress warnings, but only if I have full control over the array:

    @$array['nonExistentYet']++;
    

    Generally, it is not good to suppress warnings or error messages!