Shorthand for arrays: is there a literal syntax like {} or []?

68,017

Solution 1

Update:
As of PHP 5.4.0 a shortened syntax for declaring arrays has been introduced:

$list = [];

Previous Answer:

There isn't. Only $list = array(); But you can just start adding elements.

<?php
$list[] = 1;
$list['myKey'] = 2;
$list[42] = 3;

It's perfectly OK as far as PHP is concerned. You won't even get a E_NOTICE for undefined variables.

E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array.

As for shorthand methods, there are lots scattered all over. If you want to find them just read The Manual.

Some examples, just for your amusement:

  1. $arr[] shorthand for array_push.
  2. The foreach construct
  3. echo $string1, $string2, $string3;
  4. Array concatenation with +
  5. The existence of elseif
  6. Variable embedding in strings, $name = 'Jack'; echo "Hello $name";

Solution 2

YES, it exists!!

Extracted from another Stack Overflow question:

The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4

Usage:

$list = [];

Reference: PHP 5.4 Short Hand for Arrays

Solution 3

It is also possible to define content inside [ ] like so:

  $array = ['vaue1', 'value2', 'key3'=>['value3', 'value4']];

This will only work in php5.4 and above.

Solution 4

There are none as of PHP 5.3.

http://us.php.net/manual/en/language.types.array.php

Solution 5

Nope, it was proposed and rejected by the community, so for now only syntax for arrays is array().

Share:
68,017
James
Author by

James

Updated on July 10, 2022

Comments

  • James
    James almost 2 years

    What is the shorthand for array notation in PHP?

    I tried to use (doesn't work):

    $list = {};
    

    It will be perfect, if you give links on some information about other shorthands for PHP.

  • Popnoodles
    Popnoodles almost 10 years
    This will produce notices about undefined constants.
  • Josue Alexander Ibarra
    Josue Alexander Ibarra almost 8 years
    I've used PHP professionally for years, I had to ask a coworker what $results[] = $row; meant.
  • Daniklad
    Daniklad almost 8 years
    $results[] = $row; is actually a lot faster than array_push($results, $row)
  • Pierpaolo Cira
    Pierpaolo Cira over 7 years
    I think it is better to write 5.4 and above (in 5.6 it works). As a note it is the only working way to declare an array as a class constant (e.g. const x = ["a", "b"];) because the const x=array(....) doesn't work
  • clabe45
    clabe45 over 5 years
    For anyone who also made this mistake, use => instead of : between keys and values!
  • IncredibleHat
    IncredibleHat over 3 years
    After all this time, I thought $var = []; was introduced with PHP7. Had no idea it was as far back as 5.4 !