Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling array() without arguments of any use?

From my C++ knowledge base, I tend to initialize arrays in PHP by typing:
$foo = array()
Or I may bring this custom from Javascript, anyway, is this of any use?
As there's no problem in doing this:
$foo[45] = 'bar' without initializing it as an array, I guess not.

PS: the tags improvement is really good

like image 660
Petruza Avatar asked Aug 11 '11 14:08

Petruza


2 Answers

Yes it is. At the very least in improves readability of code (so that you don't need to wonder 'where does $foo come from? Is it empty, or is there anything in it?`.

Also it will prevent 'Variable '$a' is not set notices, or Invalid argument passed to foreach in case you don't actually assign any values to array elements.

like image 94
Mchl Avatar answered Sep 23 '22 01:09

Mchl


Either method is perfectly acceptable. As mentioned, this practice of using the array() construct is typically carried over from another language where you initialize before populating. With PHP, you can initialize an empty array and then populate later, or you can simply establish an array by assignments, such as $variableName[0] = "x";.

like image 35
Robert Avatar answered Sep 23 '22 01:09

Robert