Is calling array () without arguments of any use?

From my C ++ knowledge base, I try to initialize arrays in PHP by typing:
$foo = array()
Or can I bring this custom from Javascript, anyway, is this some kind of use?
Since there is no problem with this:
$foo[45] = 'bar' , without initializing it as an array, I think not.

PS: tag improvement is really good

+6
source share
7 answers

Yes it is. At least in improving the readability of the code (so you do not need to be surprised "where does $foo come from? Is it empty or is there anything in it?".

It will also prevent the notifications 'Variable '$a' is not set or Invalid argument passed to foreach in case you do not actually assign any values ​​to the elements of the array.

+6
source

Any method is perfectly acceptable. As already mentioned, this practice of using the array() construct is usually carried over from another language in which you initialize before filling. With PHP, you can initialize an empty array and then fill it in later or simply set the array as intended, for example $variableName[0] = "x"; .

+1
source

@petruz, that the best way to do this is not only to save you from unpleasant PHP error messages saying that the function expects the parameter to be an array, but IMHO is the best way to write code. I initialize the variable before using it.

+1
source

Initializing variables before use is good practice. Even if it is not required.

+1
source

I had problems (in older versions of PHP that I haven't tried recently) where I was working with an array with array_push or something else, and PHP barked at me. This is usually not necessary, but it can be safer, especially if you are dealing with legacy code; you might expect $ foo to be an array, but is it really a boolean? Bad things are happening.

+1
source

With initialization:

 $myArray = array(); if ($myBoolean) { $myArray['foo'] = 'bar'; } return $myArray; 

Without initialization:

 if ($myBoolean) { $myArray['foo'] = 'bar'; } return $myArray; 

In the first case, it turns out what you want if $ myBoolean is false. In the second case, this is not the case, and php may issue a warning when you try to use $ myArray later. Obviously, this is a simplified case, but in the difficult case, the β€œif” can be a few lines down and / or not even exist until someone comes and adds it later, without realizing that the array is not initialized.

While not needed, I saw a lack of initialization causing unobvious logical problems like this in complex functions that changed many times over time.

+1
source

This is a good practice. Sooner or later, you will come across a situation where you can do something like this:

 array_push($foo, '45'); 

Which will throw out the notice, and:

 $foo = array(); array_push($foo, '45'); 

will not.

+1
source

Source: https://habr.com/ru/post/894844/