Search code examples
php-8

Porting from php 5.6 to 8.2, how to express auto/init of multidimensional array?


This is now illegal if $a is not initialized at each level.

$a["a"]["b"]["c"] +=1;

Does exists a syntax to force php8.2 to behave like php5.6 and so auto-initialize the $a["a"]["b"]["c"] to value zero, if and only if not already defined to each level?


Solution

  • You can use the Null coalescing operator ?? (as of PHP 7.0), to use 0 is any element of the chain is not defined.

    Example:

    $a['a']['b']['c'] = ($a['a']['b']['c'] ?? 0) + 1;
    echo json_encode($a), PHP_EOL; // a.b.c = 1
    
    $a['a']['b']['c'] = ($a['a']['b']['c'] ?? 0) + 1;
    echo json_encode($a), PHP_EOL; // a.b.c = 2
    

    Output:

    {"a":{"b":{"c":1}}}
    {"a":{"b":{"c":2}}}
    

    https://3v4l.org/sdX97