5

Which is faster when adding variables to an array?

  1. $variable[] = $newValue;
  2. array_push($variable,$newValue);

and please mention the difference between the two if any.

Raj
  • 3,051
  • 6
  • 39
  • 57
  • 11
    Doesn't matter. Both are blazing fast and the difference is negligible. Stop overoptimising your code. Focus on real problems. – Michał Niedźwiedzki Dec 03 '10 at 10:27
  • What happenned when you tested it? – symcbean Dec 03 '10 at 10:48
  • I've had instances where array_push didn't work for multidimensional array but the direct assignment did. So, unless you are working with a very large array I say go with whichever you feel comfortable with (or works) ! – thethakuri Jul 06 '15 at 14:04

2 Answers2

17

http://www.php.net/manual/en/function.array-push.php#53289

Empy bracket doesn't check if a variable is an array first as array_push does. If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.

$variable[] seems to be a lot faster:

http://www.php.net/manual/en/function.array-push.php#83388

However if you're adding multiple values per iteration array_push() is faster:

http://www.php.net/manual/en/function.array-push.php#84959

But please remember that pre-optimization is the root of all evil. Use whatever you feel more comfortable with, and when you have a performance issue, use a profiler and do some benchmarking.

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
8

Stop doing weird things and take profiler to get real bottleneck.

ps: there is no difference.

pps: here is typical algo:

  1. Does the application speed satisfy you? If no - step 2, if yes - step 6
  2. Take the profiler
  3. Find the slowest part
  4. Optimize it so it become faster
  5. Go to step 1
  6. Get some beer
zerkms
  • 249,484
  • 69
  • 436
  • 539