Array in PHP using () or []?

Asked

Viewed 496 times

4

I always use the parentheses to define an array in PHP, such as:

$array = array('a','b','c');

But once in a while I see some codes here using brackets, like:

$array = ['a', 'b', 'c'];

However, if I use square brackets, I get the error:

Parse error: syntax error, Unexpected '[' in...

What is the correct way? Has anything to do with the PHP version? Which version accepts one thing and another?

When giving a echo phpversion(); on a PHP page of my hosting get the following version:

5.2.17

  • 2

    I believe it is the version, in mine (7.1.15) is working normally

  • I had just seen this, although I like the use with brackets, I’m using the brackets, never know if the hosting will support.

  • I didn’t know that http://www.linuxformat.com/dvdsupport

1 answer

11


According to the documentation, Short syntax array was added in the version 5.4.0 of PHP:

$array = ['a', 'b', 'c'];

When executing the above code in a lower version than 5.4, will get the error informed, already the other notation has been added in the version 4 from PHP which the documentation has been removed.

Which way is right?

Both are correct if they are being used in a compatible version!

Which version accepts one thing and another?

# PHP 4 ~> 7.x
$array = array('a','b','c');

# PHP 5.4.x ~> 7.x
$array = ['a', 'b', 'c'];
  • Because eh, my stay is very late. Thanks for the answer. very good!

  • But taking advantage, one question strikes me: this version that I use is still good or bad tah?

  • Ta bad even rs.

  • You can choose the version you want! But honestly, I wouldn’t have that option, since newer version has fixes and improvements, I would give only the version 5.6 and the 7.x for choice. But, looking at the earning who cares right ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.