Difference between array_push() and $array[] =

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[] = because in that way there is no overhead of calling a function.

For example :

$arr = array();
array_push($arr, "stackoverflow");
print_r($arr);

vs

$arr[] = "stackoverflow";
print_r($arr);

I don't understand why there is a big difference.


Solution 1:

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[].

Solution 2:

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.

Solution 3:

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.

Solution 4:

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.