Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What's the difference between initializing an array with "new" vs without it?

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!

like image 822
mattypie Avatar asked Nov 16 '10 19:11

mattypie


2 Answers

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.

like image 50
bcosca Avatar answered Oct 09 '22 18:10

bcosca


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.

like image 24
JAL Avatar answered Oct 09 '22 16:10

JAL