Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize (empty) array in PHP

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?
}
like image 210
Tom Auger Avatar asked May 11 '11 15:05

Tom Auger


People also ask

How do I create an empty array in PHP?

Syntax to create an empty array: $emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.

How do you initialize an empty array?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.


8 Answers

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

Cheers,

-=Cameron

like image 132
C Landreaux Avatar answered Oct 02 '22 07:10

C Landreaux


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

like image 26
Andy E Avatar answered Oct 02 '22 06:10

Andy E


Prior to PHP 5.4:

$myArray = array();

PHP 5.4 and higher

$myArray = [];
like image 35
Md. Shafiqur Rahman Avatar answered Oct 02 '22 06:10

Md. Shafiqur Rahman


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

like image 24
Adrian Avatar answered Oct 02 '22 07:10

Adrian


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()

like image 24
James C Avatar answered Oct 02 '22 07:10

James C


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

like image 41
improgrammer Avatar answered Oct 02 '22 06:10

improgrammer


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

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

like image 29
Matthieu Napoli Avatar answered Oct 02 '22 07:10

Matthieu Napoli


Try this:

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

    // will print
    // array(0) { }
like image 40
Pyetro Avatar answered Oct 02 '22 06:10

Pyetro