PHP array vs [ ] in method and variable declaration

from PHP docs:

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

if you'd try using '[]' notation in earlier version than 5.4, it will fail, and PHP will throw a syntax error

for backward-compatibility you should use array() syntax.


PSR-2 and PSR-12 (by PHP Framework Interoperability Group) do not mention short array syntax. But as you can see in chapter 4.3 they use short array syntax to set the default value of $arg3 to be an empty array.

So for PHP >= 5.4 the short array syntax seems to be the de-facto standard. Only use array(), if you want your script to run on PHP <5.4.


That depends on what version of PHP you are targeting. For the best backward compatibility, I'd recommend you to use array(). If you don't care about older versions (< PHP 5.4), I'd recommend you to use a shorter version.


just made a test to see how [] performs vs array() here is what I got

testing 1 million []s ( with $arr[] = [] )
started at : 1561298821.8754
ended at: 1561298822.6881
difference: 0.81266021728516 seconds 

testing 1 million array()s ( with array_push( $arr, array()) )
started at : 1561298822.6881
ended at: 1561298823.843
difference: 1.1549289226532 seconds 

testing 1 million []s ( again while the processor is hotter)
started at : 1561298823.8431
ended at: 1561298824.7448
difference: 0.9017219543457 seconds 

so [] performed about 20% faster

Tags:

Php

Standards