PHP array vs [ ] in method and variable declaration

PhpStandards

Php Problem Overview


I have a question about PHP syntax.

When defining functions and variables, which convention should I use?

I know they do the same thing in practice but I would like to know which method conforms to best practice standards.

Variables

public $varname = array();

or

public $varname = [];

Methods

public function foo($bar = array()){}

or

public function foo($bar = []){}

Php Solutions


Solution 1 - Php

PSR-2 (by PHP Framework Interoperability Group) does 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.

Solution 2 - Php

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.

Solution 3 - Php

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

Solution 4 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDieter GribnitzView Question on Stackoverflow
Solution 1 - PhpBreyndotEchseView Answer on Stackoverflow
Solution 2 - PhpNitsan BaleliView Answer on Stackoverflow
Solution 3 - PhpAurangzebView Answer on Stackoverflow
Solution 4 - PhpValentin RodyginView Answer on Stackoverflow