Difference between array_push() and $array[] =

前端 未结 9 1956
梦毁少年i
梦毁少年i 2020-12-02 07:06

In the PHP manual, (array_push) says..

If you use array_push() to add one element to the array it\'s better to use $array[]

相关标签:
9条回答
  • 2020-12-02 07:33

    I know this is an old answer but it might be helpful for others to know that another difference between the two is that if you have to add more than 2/3 values per loop to an array it's faster to use:

         for($i = 0; $i < 10; $i++){
              array_push($arr, $i, $i*2, $i*3, $i*4, ...)
         }
    

    instead of:

         for($i = 0; $i < 10; $i++){
             $arr[] = $i;
             $arr[] = $i*2;
             $arr[] = $i*3;
             $arr[] = $i*4;
             ...
         }
    

    edit- Forgot to close the bracket for the for conditional

    0 讨论(0)
  • 2020-12-02 07:34

    explain: 1.the first one declare the variable in array.

    2.the second array_push method is used to push the string in the array variable.

    3.finally it will print the result.

    4.the second method is directly store the string in the array.

    5.the data is printed in the array values in using print_r method.

    this two are same

    0 讨论(0)
  • 2020-12-02 07:36

    No one said, but array_push only pushes a element to the END OF THE ARRAY, where $array[index] can insert a value at any given index. Big difference.

    0 讨论(0)
  • 2020-12-02 07:38

    You should always use $array[] if possible because as the box states there is no overhead for the function call. Thus it is a bit faster than the function call.

    0 讨论(0)
  • 2020-12-02 07:40

    both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element

    0 讨论(0)
  • 2020-12-02 07:41

    The difference is in the line below to "because in that way there is no overhead of calling a function."

    array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

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