phpvariablesforeachdefaultisset

Set multiple variables to the same if they are not set


Is there a shorthand for the following:

$a ??= []; # Note: $a ??= [] is equivalent to $a = isset($a) ? $a : []
$b ??= [];
#...
$z ??= [];

One possible solution is:

foreach (array("a", "b", ..., "z") as $elem) {
  $$elem ??= [];
}

What I do not like about the approach above is that I am passing a list of strings to the foreach function rather than a list of variables - that would be inconvenient if the names of the variables were to change. Is there another more convenient solution?


Solution

  • You can use by reference variable-length argument lists: (PHP >= 7.4)

    function defineVariables($default, &...$vars)
    {
        foreach($vars as &$v)
            $v ??= $default;
    }
    
    defineVariables([], $a, $b, $c);