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
Answers
in php, you can achieve this using variable variables. here’s a more concise and dynamic solution:
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’.
You can use by reference variable-length argument lists: (PHP >= 7.4)