Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Difference between array() and []

People also ask

What is the difference between array () and [] in PHP?

Note: Only the difference in using [] or array() is with the version of PHP you are using. In PHP 5.4 you can also use the short array syntax, which replaces array() with [].

What does array [] mean in PHP?

Advertisements. An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

What is a [] in PHP?

If you are using 5.4 or later version of PHP then you can use either array() or [] to create an array, associative array or even multidimensional array.

What are square brackets PHP?

In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array. Ordered Arrays.


Following [] is supported in PHP >= 5.4:

['name' => 'test', 'id' => 'theID']

This is a short syntax only and in PHP < 5.4 it won't work.


As of 2019, it has been 7 years since the [] syntax was added. That is long enough to drop array() except in old legacy programs, in my opinion.


If you are using 5.3 or previous version then you can't use [] as an array as well as associative array. If you are using 5.4 or later version of PHP then you can use either array() or [] to create an array, associative array or even multidimensional array.


And regarding the <?= ?> part of the question: it is largely not frowned upon, at least not in 2019.

  1. A good technical breakdown: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
  2. A note in PSR-1: Files MUST use only <?php and <?= tags.
  3. TL;DR: There is no reason you cannot or should not use it.