338

In certain other languages (ActionScript 3 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. Are there are any equivalences in PHP?

class Foo {
    private $arr = array(); // Is there another / better way?
}
5
  • 12
    That's all I ever do. Commented 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. Commented May 11, 2011 at 17:08
  • 1
    This question helps a lot Commented Mar 31, 2014 at 13:13
  • try array_fill ? php.net/manual/en/function.array-fill.php Commented 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 = [] Commented Dec 3, 2015 at 15:46

9 Answers 9

268
$myArray = [];

Creates an 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 it’s all in the PHP documentation.

Sign up to request clarification or add additional context in comments.

6 Comments

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().
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.
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.
To be fair, this actually answers the OP's question.
lol... Mind blown. Decades of PHP and I'm just learning you don't need array_push.
|
211

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 Comments

Possibly the 5.4 change was made because people who could spell "which" took over the voting process :)
I prefer $array = []; as it makes going back and forth between JS and PHP easier.
So Is $array = []; better option ??? or should I try other one. which one is better
@hitesh: it's a matter of personal preference. They're both exactly the same functionally, [] is just a little easier to type.
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.
|
71

Prior to PHP 5.4:

$myArray = array();

PHP 5.4 and higher

$myArray = [];

Comments

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 Comments

The best answer IMO: there are different syntaxes, but regarding performances they all are the same.
Is there performance issue involved for both ..where can i check about this .. any link or doc
As a result, until you're sure your code will never be run on pre 5.4 environments, use $array = new array()
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 Comments

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 you'd access them like $this->arr and $this->_arr. Why should you never use public properties?!
6

Initializing a simple array:

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

Initializing an array within an array:

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

Source: Source for the code

3 Comments

The original question was about how to initialize an empty array.
came here for this, but wished you had used the short version instead the ancient array()
$array1 = [ 1, 2, 3, 4 ];
4

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

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

3 Comments

This is no longer the case, 5.4 introduced shorthand syntax for arrays.
@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.
@Motes People lose the rep gain from the answer when they delete it. It's better to edit it.
3

Try this:

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

    // will print
    // array(0) { }

2 Comments

Kinda cool, but more as a party trick than a really useful coding pattern, don't you think?
Could be useful if you wanna create your array in an object with properties pattern and convert it to array in the end.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.