0

Possible Duplicate:
Php array_push() vs myArray[]

Hello folks.

I know some ways to add an element to an array in PHP.

$anArray[] = $newElement; <-I like this one

array_push() <-I've seen many people use it.

There are others, I'm sure.

I'd like to know which of these is more efficient or if there's another way of doing it more efficiently.

NOTE: I just want to add an element, could be at the end of the array. I mean that I won't specify what position the new element is to be added at.

Community
  • 1
  • 1
Felipe
  • 11,557
  • 7
  • 56
  • 103

3 Answers3

2

The assign operator will be slightly faster [there's no need to do a function call], but with array_push(), you can append more than one variable at once.

Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
1

None are more efficient than others.

PHP is a high-level language, and for the most part simple equivalent operations like these generate exactly the same opcodes.

In the rare case that there is a difference in the low-level code produced, it's at a level so fast that attempts to manipulate them would count as micro-optimisations.

In conclusion, simply don't worry about it. Write PHP code that does what it says it does and you'll be fine.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I know the difference might be slight. But if within a loop of, say, ten thousand iterations, these small differences might add up to something noticeable. – Felipe May 21 '11 at 00:38
  • @Felipe: Granted, technically speaking that is possible. However, the compilation process will almost always render things like this completely null and void when the semantics are the same. _Trust_ your compiler, even [or especially] when it's PHP so the compilation process is implicit. – Lightness Races in Orbit May 21 '11 at 00:40
0

Actually, it depends on what you are trying to accomplish. Are just adding a value to an array, regardless of the array key, or does the array key have to be specific? The first way you have suggested allows you to assign a custom key to the value, the array_push() will simply assign a numeric key one greater than the previous one.

Also, array_push() will allow you to add multiple values to an array at one time, like this:

array_push($myArray, "value1", "value2", "value3");

You can do the same with your first method, it would just be a lot of repetition. :)

If the key doesn't matter, or only need to add one value, then I would just say it is a matter of opinion.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195