Difference between array_push() and $array[] =

前端 未结 9 1957
梦毁少年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:41

    array_push — Push one or more elements onto the end of array

    Take note of the words "one or more elements onto the end" to do that using $arr[] you would have to get the max size of the array

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

    You can add more than 1 element in one shot to array using array_push,

    e.g. array_push($array_name, $element1, $element2,...)

    Where $element1, $element2,... are elements to be added to array.

    But if you want to add only one element at one time, then other method (i.e. using $array_name[]) should be preferred.

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

    When you call a function in PHP (such as array_push()), there are overheads to the call, as PHP has to look up the function reference, find its position in memory and execute whatever code it defines.

    Using $arr[] = 'some value'; does not require a function call, and implements the addition straight into the data structure. Thus, when adding a lot of data it is a lot quicker and resource-efficient to use $arr[].

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