Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to declare PHP array before adding values with []?

Tags:

arrays

php

$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.

like image 283
ryanve Avatar asked Nov 23 '11 16:11

ryanve


People also ask

Can we declare an array without defining a size or adding any elements at the time of declaration?

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.

Do arrays need to be declared?

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.

Why we need to declare an array?

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.


2 Answers

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.

like image 87
djdy Avatar answered Sep 23 '22 01:09

djdy


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.

like image 29
Charles Sprayberry Avatar answered Sep 20 '22 01:09

Charles Sprayberry