Best way to initialize (empty) array in PHP

前端 未结 8 1603
悲&欢浪女
悲&欢浪女 2020-12-02 05:25

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

相关标签:
8条回答
  • 2020-12-02 06:01

    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

    0 讨论(0)
  • 2020-12-02 06:02
    $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

    0 讨论(0)
提交回复
热议问题