Search code examples
phpnotationshorthand

Is there a shorthand notation for initialising associative arrays or objects in PHP, like the one introduced to JavaScript with ES2015?


With ES2015, a shorthand notation for object initialisation was introduced to JS in the form of

let a = 'foo', b = 'bar', c = 'baz';
let o = {a, b, c};

// result:
{ a: "foo", b: "bar", c: "baz" }

I wonder if there's something similar in PHP7, so that if I had the variables $a, $b, and $c, I'd get an associative array with the keys corresponding to the variable names and the values to their values:

$a = 'foo'; $b = 'bar'; $c = 'baz';
// $o = ????

// expected result equal to
array('a' => $a, 'b' => $b, 'c' => $c)

Solution

  • As you did it in JS, you can collect all variables by their names in array and do compact():

    $a = 'foo'; $b = 'bar'; $c = 'baz';
    
    $ar=['a','b','c'];
    print_r(compact($ar));
    

    Output:

    Array
    (
        [a] => foo
        [b] => bar
        [c] => baz
    )
    

    Or just do compact('a', 'b', 'c'); as well.

    Demo