320

In certain other languages (AS3 for example), it has been noted that initializing a new array is faster if done like this var foo = [] rather than var foo = new Array() for reasons of object creation and instantiation. I wonder whether there are any equivalences in PHP?

class Foo {
    private $arr = array(); // is there another / better way?
}
5
  • 12
    That's all I ever do.
    – Matt
    May 11, 2011 at 15:28
  • 2
    Thanks to everyone who answered (and so quickly!). I had to arbitrarily select an answer so Andy's seemed to be the most in-depth.
    – Tom Auger
    May 11, 2011 at 17:08
  • 1
    This question helps a lot
    – Hitesh
    Mar 31, 2014 at 13:13
  • try array_fill ? php.net/manual/en/function.array-fill.php
    – zx1986
    Dec 3, 2015 at 7:25
  • 2
    @zx1986 that's a pretty cumbersome way of creating an empty array. Certainly less than the OP $arr = array() or $arr = []
    – Tom Auger
    Dec 3, 2015 at 15:46

9 Answers 9

248
$myArray = []; 

Creates empty array.

You can push values onto the array later, like so:

$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";

At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.

Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.

You actually have to use the unset() function to remove items:

unset($myArray[1]); 

... would remove "house" from the array (arrays are zero-based).

unset($myArray); 

... would destroy the entire array.

To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:

$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";

You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.

So if you do this:

$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";

... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.

6
  • 7
    It's important to note that $ary = [] only works post PHP 5.4. From a performance perspective however there's no advantage to [] vs. array().
    – Tom Auger
    Jan 8, 2015 at 14:45
  • 1
    For earlier versions you can use array_push() w3schools.com/php/func_array_push.asp I do not know if there is a performance hit associated with this.
    – Mark
    Apr 27, 2015 at 23:12
  • 3
    You misunderstood @TomAuger's point @Mark. $array[] = 'foo' works just fine in older versions of PHP. It's only $array = []; to initialise an array that is new in 5.4.
    – Codemonkey
    Nov 26, 2015 at 9:16
  • 1
    To be fair, this actually answers the OP's question.
    – Smitty
    Jan 24, 2018 at 15:19
  • 1
    lol... Mind blown. Decades of PHP and I'm just learning you don't need array_push.
    – Bangkokian
    Aug 14, 2019 at 14:26
208

In ECMAScript implementations (for instance, ActionScript or JavaScript), Array() is a constructor function and [] is part of the array literal grammar. Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.

PHP, on the other hand, has language constructs that may look like functions but aren't treated as such. Even with PHP 5.4, which supports [] as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.

// Before 5.4, you could only write
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// As of PHP 5.4, the following is synonymous with the above
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

If you need to support older versions of PHP, use the former syntax. There's also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me.  I actually made the mistake of trying to initialise arrays using [] when I was first learning PHP.

This change to the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:

This patch will not be accepted because slight majority of the core developers voted against. Though if you take a accumulated mean between core developers and userland votes seems to show the opposite it would be irresponsible to submit a patch witch is not supported or maintained in the long run.

However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).

6
  • 52
    Possibly the 5.4 change was made because people who could spell "which" took over the voting process :)
    – Rob Grant
    Jan 3, 2014 at 9:33
  • 44
    I prefer $array = []; as it makes going back and forth between JS and PHP easier.
    – Justin
    Mar 20, 2014 at 20:17
  • So Is $array = []; better option ??? or should I try other one. which one is better
    – Hitesh
    Mar 31, 2014 at 13:14
  • 2
    @hitesh: it's a matter of personal preference. They're both exactly the same functionally, [] is just a little easier to type.
    – Andy E
    Mar 31, 2014 at 13:35
  • 8
    The [] syntax seems to be universally preferred, but it's important to note that there a large number of hosts still using 5.3 exclusively. If you want to distribute your code, the [] syntax will fatal out.
    – etc
    Nov 21, 2014 at 1:44
67

Prior to PHP 5.4:

$myArray = array();

PHP 5.4 and higher

$myArray = [];
1
  • And how can we make multidimensional array using PHP 5.4 or higher?
    – Siraj Alam
    Jun 3, 2018 at 12:51
26

In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.

3
  • 1
    The best answer IMO: there are different syntaxes, but regarding performances they all are the same. Jul 22, 2012 at 12:40
  • 1
    Is there performance issue involved for both ..where can i check about this .. any link or doc
    – Hitesh
    Mar 31, 2014 at 13:16
  • 2
    As a result, until you're sure your code will never be run on pre 5.4 environments, use $array = new array()
    – Tom Auger
    Sep 10, 2014 at 18:12
20

What you're doing is 100% correct.

In terms of nice naming it's often done that private/protected properties are preceded with an underscore to make it obvious that they're not public. E.g. private $_arr = array() or public $arr = array()

2
  • 2
    In php, i think it's better not to name them with an underscore since you always use $this to get the value and should never use public properties.
    – meze
    May 11, 2011 at 15:34
  • 1
    @meze you'd access them like $this->arr and $this->_arr. Why should you never use public properties?!
    – James C
    May 11, 2011 at 15:36
5

Initializing a simple array :

<?php $array1=array(10,20,30,40,50); ?>

Initializing array within array :

<?php  $array2=array(6,"santosh","rahul",array("x","y","z")); ?>

Source : Sorce for the code

2
  • 3
    The original question was about how to initialize an empty array.
    – Tom Auger
    Dec 16, 2014 at 16:46
  • came here for this, but wished you had used the short version instead the ancient array()
    – clockw0rk
    Sep 16, 2020 at 15:21
4

There is no other way, so this is the best.

Edit: This answer is not valid since PHP 5.4 and higher.

3
  • This is no longer the case, 5.4 introduced shorthand syntax for arrays.
    – Andy E
    Jul 22, 2012 at 7:32
  • 13
    @Motes Why so much hate :'( ? Kidding aside, I've made it more explicit by "striking" the old answer. It could still be useful for a newbie to understand that the answer has changed. Oct 17, 2013 at 16:22
  • @Motes People lose the rep gain from the answer when they delete it. It's better to edit it.
    – mbomb007
    Jul 10, 2019 at 20:39
4

Try this:

    $arr = (array) null;
    var_dump($arr);

    // will print
    // array(0) { }
2
  • 4
    Kinda cool, but more as a party trick than a really useful coding pattern, don't you think?
    – Tom Auger
    Feb 26, 2014 at 18:15
  • Could be useful if you wanna create your array in an object with properties pattern and convert it to array in the end. Dec 8, 2015 at 8:30
0

Do not do this:

$arrTst = array( 'IdxKeyOne' => null, 'IdxKeyTwo' => null, 'IdxKeyThr' => null );

There's no such thing as "initializing" an array's index-keys with dummy/placeholder values. print_r gives:

Array (
  [IdxKeyOne] => 
  [IdxKeyTwo] => 
  [IdxKeyThr] => 
)

where the elements exist, having defined keys but null-values. When using the array later, you would have to drop the dummy-row anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.