Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array vs [ ] in method and variable declaration

Tags:

php

standards

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 = []){} 
like image 256
Dieter Gribnitz Avatar asked Oct 30 '14 11:10

Dieter Gribnitz


People also ask

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is difference between array and [] in PHP?

The ONLY difference between [] and array() is syntactic, since [] is an abbreviation for array().

Do we need to declare array in PHP?

Unless you like notices about undeclared variables, I would recommend to initialize. Plus, it just makes for legible code (it's clear that $foo = array() and that it wasn't a string turned in to an array, etc.).

How do you declare an array variable in PHP?

To create an array, you use the array() construct: $myArray = array( values ); To create an indexed array, just list the array values inside the parentheses, separated by commas.


1 Answers

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.

like image 171
BreyndotEchse Avatar answered Sep 22 '22 03:09

BreyndotEchse