skip to Main Content

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


  1. 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’.

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search