122

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.

Charity Leschinski
  • 2,886
  • 2
  • 23
  • 40
l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • 9
    One is a function call, the other one isn't. Exactly what is mentioned in the box. – KingCrunch Jan 09 '13 at 10:11
  • 1
    One is the function call as mentioned above which means use of some resources to switch control to/from function call (thus resulted in overhead processing). Whereas, later is simply assigning new element into the array straight away. – Ghazanfar Mir Jan 09 '13 at 10:16
  • 2
    this question saved me alot of time pushing to arrays :) – RozzA Aug 13 '15 at 19:54

10 Answers10

157

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

BenM
  • 52,573
  • 26
  • 113
  • 168
  • 4
    what if such notation "$arr[] = 'some value';" boils down to the call of function? – Tebe Jul 07 '14 at 13:52
  • 1
    @gekannt How would that happen? Do you mean if 'some value' in your comment is a closure? That would store the reference of the closure in to the array. If you mean that 'some value' is a function that gets invoked, it would add whatever that function returns. – Kirkland Aug 11 '14 at 17:11
  • @Kirkland Operators are just functions with an alternative syntax in most C-like languages, I'm no PHP expert, but I can imagine they implemented operators the same way since it's a C dialect. – Kevin Jan 04 '17 at 08:01
  • 2
    @Kevin: thou I agree with you and I'm pretty sure there is a function behind the alternate syntax its not the one mentioned above as I see the fallowing comment in the php documentation: "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." don't have time now to see exactly what is behind it as the search term is bit confusing for search engines :) – jnhghy - Alexandru Jantea Jun 16 '17 at 14:29
  • 1
    Is there any actual evidence that `$arr[] = value` is faster? Trying to imagine why the compiler would treat the code any differently. – c.. Apr 30 '20 at 21:24
  • 2
    @c.. - Presumably the compiler difference is because `array_push` allows multiple values to be pushed, and that was easier to implement as a function. – ToolmakerSteve Dec 02 '20 at 23:28
  • @ToolmakerSteve not really. You could also do this without using array_push. `$array = array('stackoverflow'); $add = array('rocks'); $array[] = $add;` The output look the same as `array_push($array,$add). So in my opinion it is a useless function and I never ever use it in my code. – Alexander Behling Feb 17 '21 at 15:41
  • @AlexanderBehling - I never use it either. The person asking was wondering why `array_push(a, v)` didn't compile into `a[] = v`. That person likely wasn't aware that it could take multiple parameters. From an **implementation** standpoint, given that there was already a mechanism for functions to handle multiple parameters, making it a function required no extra implementation work. (What you suggest would have required a little extra implementation code, to convert one syntax tree into another.) That its a useless function is beside the point. – ToolmakerSteve Feb 18 '21 at 19:59
  • @AlexanderBehling - and now that I think about it, creating an array, and then pushing its elements, would also not be as fast as the single-element syntax. Bottom line: **implementer didn't bother optimizing the single-parameter case of array_push; that's really the answer to c's comment.** – ToolmakerSteve Feb 18 '21 at 20:06
  • There's the possibility that $array[] is just syntactical sugar, and he's wrong about it being faster. – Kaz Vorpal Dec 20 '22 at 14:35
45

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.

Sujit Singh
  • 921
  • 1
  • 10
  • 20
  • Is it bad practice to combine the two as needed throughout a project? – PBwebD Sep 03 '16 at 18:01
  • 2
    @testing123 Absolutely not. It's a good practice to use the most efficient solution available at hand, unless it severely cripples readability, compatibility, etc (or if you need to obey certain style guides). – Chris Kraszewski Jul 10 '17 at 12:28
  • Combining with argument unpacking makes `array_push($arr1, ...$arr2)` possible. It can be orders of magnitude faster than `$arr1 = array_merge(arr1, $arr2)` in cases where many arrays are being combined. – Jon Hulka Aug 13 '21 at 22:30
17

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.

halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
Baig
  • 301
  • 3
  • 9
  • 5
    I did not say that it was a reason. In the question, difference was asked and this is also the difference – Baig Jan 09 '13 at 10:21
  • Good observation; therefore it is a contribution to the discussion. Someone googling might reach this Q&A, based on its title. (Even though, strictly speaking, it isn't what OP wanted to know. They were asking about the sentence they quote, not about other differences between the two.) – ToolmakerSteve Feb 18 '21 at 20:11
7

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.

Benjamin Paap
  • 2,744
  • 2
  • 21
  • 33
4

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

user1909426
  • 1,658
  • 8
  • 20
ianace
  • 1,646
  • 2
  • 17
  • 31
  • 1
    Re *"to do that using $arr[] you would have to get the max size of the array"*. No, you are confusing `$arr[...index...] = $value;` with what is being discussed here, which is `$arr[] = $value;`. Don't need to know the size or array, to push on the end. Multiple elements would simply be multiple calls: `$arr[] = $value1; $arr[] = $value2; $arr[] = $value3;` – ToolmakerSteve Apr 12 '19 at 08:17
2

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

1

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

Sara
  • 103
  • 1
  • 1
  • 7
1

Thought I'd add to the discussion since I believe there exists a crucial difference between the two when working with indexed arrays that people should be aware of. Say you are dynamically creating a multi-dimensional associative array by looping through some data sets.

$foo = []
foreach ($fooData as $fooKey => $fooValue) {
    foreach ($fooValue ?? [] as $barKey => $barValue) {

        // Approach 1: results in Error 500
        array_push($foo[$fooKey], $barKey); // Error 500: Argument #1 ($array) must be of type array
        // NOTE: ($foo[$fooKey] ?? []) argument won't work since only variables can be passed by reference

       // Approach 2: fix problem by instantiating array beforehand if it didn't exist
       $foo[$fooKey] ??= [];
       array_push($foo[$fooKey], $barKey);

        // Approach 3: One liner approach
        $foo[$fooKey][] = $barKey; // Instantiates array if it doesn't exist
    }
}

Without having $foo[$fooKey] instantiated as an array beforehand, we won't be able to do array_push without getting the Error 500. The shorthand $foo[$fooKey][] does the heavy work for us, checking if the provided element is an array, and if it isn't, it creates it and pushes the item in for us.

Nikola
  • 35
  • 7
0

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

  • 1
    I wonder how this compares to array_merge. E.g. `for(...){ $arr = $arr + [$i, $i*2, $i*3, $i*4, ...] }`. I speculate array_push is still slightly faster than that. – ToolmakerSteve Apr 12 '19 at 08:06
-1

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.

Marco
  • 2,757
  • 1
  • 19
  • 24
  • The question was the "Difference between array_push() and $array[] =" what i've said is one difference. A big one! – Marco Apr 12 '19 at 12:10
  • 3
    I respectfully disagree. You are describing `$array[index] = `, which is a *different operation* than `$array[] = ...`. The question gives two pieces of code, and asks why there would be *a significant [performance] difference* between them. The question literally means `$array[] = ...`, which is a specific php idiom, that does not involve an index. array + index solves a different problem, yields different code, and is a different tradeoff. – ToolmakerSteve Apr 12 '19 at 12:53