$arr = array(); // is this line needed? $arr[] = 5;
I know it works without the first line, but it's often included in practice.
What is the reason? Is it unsafe without it?
I know you can also do this:
$arr = array(5);
but I'm talking about cases where you need to add items one by one.
You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable.
Arrays are used when there is a need to use many variables of the same type. It can be defined as a sequence of objects which are of the same data type. It is used to store a collection of data, and it is more useful to think of an array as a collection of variables of the same type. Arrays can be declared and used.
If you don't declare a new array, and the data that creates / updates the array fails for any reason, then any future code that tries to use the array will E_FATAL
because the array doesn't exist.
For example, foreach()
will throw an error if the array was not declared and no values were added to it. However, no errors will occur if the array is simply empty, as would be the case had you declared it.
Just wanted to point out that the PHP documentation on arrays
actually talks about this in documentation.
From the PHP site, with accompanying code snippet:
$arr[key] = value; $arr[] = value; // key may be an integer or string // value may be any value of any type
"If
$arr
doesn't exist yet, it will be created, so this is also an alternative way to create an array."
But, as the other answers stated...you really should declare a value for your variables because all kind of bad things can happen if you don't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With