0

I'm getting an error when I try to set an array using

$var = []; // throws error
$var = array(); // no error

The error is

Parse error: syntax error, unexpected '[' 

Never seen this before! I assume it's a quirk in a version of PHP? It's also throwing the same error when I do something like:

$var[] = $newvalue;
8
  • 1
    Which version of PHP are you using? Commented Sep 30, 2014 at 22:52
  • I've never initialised an array with $var = []; but always with $var = array(); but maybe that's just me Commented Sep 30, 2014 at 22:54
  • Really? It always use [], but never for my answers on SO because it'll lead to people commenting -- oh syntax error. Commented Sep 30, 2014 at 22:55
  • never even seen any one do that, oh well learn something new every day Commented Sep 30, 2014 at 22:57
  • I guess I've just been using PHP 5.4 for so long I got used to it. Commented Sep 30, 2014 at 23:13

2 Answers 2

4

$var = []; is legal as of PHP 5.4.

Sign up to request clarification or add additional context in comments.

Comments

1

It's not a "quirk in a version", but it does require a minimum version: the "short array syntax" ([] as a synonym for array()) was introduced in PHP 5.4, as can be seen from the release notes of that version.

You can also check which versions of PHP a piece of code will work in using the online tool at http://3v4l.org, which runs a snippet of code in a wide variety of builds, from PHP 4 to what will eventually be PHP 7, and even various versions of HHVM. Here is an example of running this code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.