I've always created arrays by just populating them
$foo[] = 'car';
but I've seen a lot of
$foo = array();
$foo[] = 'car';
and
$foo = new array();
What's the difference between not initializing, using array(), and using new array();?
thanks!
You don't instantiate an array in PHP using:
$foo=new array(); // error in PHP
That's for Javascript:
foo=new Array(); // no error in Javascript
In PHP, new
is used only for instantiating objects.
The difference is that using new
does not work, since array()
is a language construct and not an object constructor. It throws an error:
Parse error: syntax error, unexpected T_ARRAY in php shell code on line 1
On the other hand, declaring it like
$f=array();
before you start assigning items is a good practice. Strict error reporting mode may give a warning about using an undeclared variable otherwise.
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