Set multiple variables to the same if they are not set

70 Views Asked by At

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?

2

There are 2 best solutions below

4
shingo On BEST ANSWER

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);
1
R.tbr On

in php, you can achieve this using variable variables. here's a more concise and dynamic solution:

foreach (range('a', 'z') as $letter) {
    ${$letter} ??= [];
}

this code dynamically creates variables $a through $z and initializes them to an empty array if they are not already set. this way, you don't need to pass a list of variable names explicitly. Instead, it dynamically generates them based on the range of letters from 'a' to 'z'.