137

What's better to use in PHP for appending an array member,

$array[] = $value;

or

array_push($array, $value);

?

Though the manual says you're better off to avoid a function call, I've also read $array[] is much slower than array_push(). What are some clarifications or benchmarks?

1
  • 2
    $myArray[] = 123; This will be faster than array_push function. It directly adds the value into that array. Function has separate stack for that variables. and it may have that statement inside that function,.
    – sganesh
    Mar 12, 2010 at 9:32

9 Answers 9

180

I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.

I ran this code:

$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    $array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
    array_push($array, $i);
}
print microtime(true) - $t;

The first method using $array[] is almost 50% faster than the second one.

Some benchmark results:

Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]

Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]

Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]

This shouldn't be surprising, as the PHP manual notes this:

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.

The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.

13
  • 12
    Micro-optimisations like these are rarely worth the effort. If you are writing it from scratch, do it how makes most sense, and only then, if it's a little slow to produce a page, profile it. The chances of getting all the way down to having to change something like this to speed things up is slight. May 31, 2009 at 8:09
  • 5
    Just to make sure, since the code seems to mismatch the output, I verified that $array[] is indeed much faster, 300ms vs. 2000ms for 1M assignments on my machine. However, adding 20 items at once in array_push was about as fast as 20 $array[] =s.
    – Elle
    May 25, 2015 at 17:13
  • 7
    @AlisterBulman Micro-optimizations are not worth the effort if you're thinking about going back through your whole codebase and 'optimizing' it. However, if you have several different ways of doing the same thing and are aware that one way is better (even just a little) than the others, you can make it your habit to use that way. Why wouldn't you do this? Feb 18, 2016 at 7:47
  • 3
    @AlisterBulman I must strongly disagree, or at least partially, if you know better, write better, but don't put much effort to searching for possible micro-optimisation...
    – jave.web
    Feb 16, 2017 at 20:13
  • 2
    Reminder to any onlooker: not all minor optimization is the "premature optimization" that is the root of all evil as said Knuth. Some little faster things are just little faster things. remembering $array[]=$s is ok, combing your codebase for array_push isn't. Don't prematurely beat the premature-optimization-is-evil drum just because it exists.
    – Plasmarob
    May 31, 2018 at 20:18
46

The main use of array_push() is that you can push multiple values onto the end of the array.

It says in the 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.

1
  • That's right. Does anyone know a real world scenario where you have to add multiple values to an array at once? It seems to me that this must be a very rare scenario because I'm writing PHP since 2004 (where PHP4 was still actual) and I have never ever used it. Sep 21, 2021 at 14:46
37

From the PHP documentation for array_push:

Note: 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.

1
  • 1
    Funny how your answer was first, but is the less voted on.
    – T.Woody
    Sep 4, 2019 at 16:47
25

Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...

"Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "

10
  • 10
    Huh? PHP's array functions are awesome.
    – cletus
    Feb 18, 2009 at 4:56
  • 18
    Functionally they are awesome, yes, but he was referring to the inconsistent naming scheme.
    – ryeguy
    Feb 18, 2009 at 5:03
  • 2
    You should turn on parameter hinting in your IDE. But I agree, some consistency would have been great.
    – Pim Jager
    Feb 18, 2009 at 11:50
  • 4
    I do agree on this. There is no consistency neither in the naming scheme (x_y or xy or y_x ...) nor in the parameters logic (pass the target object first, last, between arrays, strings and regexps, good luck to find a common rule!).
    – Déjà vu
    Nov 19, 2010 at 3:40
  • 5
    FWIW, I like the needle/haystack naming convention and find it easy to remember, as it goes in the same order as the phrase: "like finding a needle (1) in a haystack (2)"
    – rybo111
    Aug 1, 2014 at 9:39
8

One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.

$myArray = array();
array_push($myArray, 1,2,3,4);
echo join(',', $myArray);

prints 1,2,3,4

2

A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.

2

Since "array_push" is a function and it called multiple times when it is inside the loop, it will allocate memory into the stack.

But when we are using $array[] = $value then we are just assigning a value to the array.

1

Second one is a function call so generally it should be slower than using core array-access features. But I think even one database query within your script will outweight 1000000 calls to array_push().

See here for a quick benchmark using 1000000 inserts: https://3v4l.org/sekeV

1
  • Can you substantiate your claim, e.g. with some rough calculations? Please respond by editing (changing) your answer, not here in comments (but without "Edit:", "Update:", or similar - the answer should appear as if it was written today). Aug 12, 2021 at 19:56
0

I just wan't to add : int array_push(...) returns the new number of elements in the array (PHP documentation). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);.

Also array_push(...) is meaningful when variable is used as a stack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.