30

I need to add values received from MySQL into an array (PHP). Here is what I've got:

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    $players[] = $homePlayerRow['player_id'];
}

Is this the only way of doing it?

Also, is the following faster/better?

$players = array();

while ($homePlayerRow = mysql_fetch_array($homePlayerResult)) {
    array_push($players, $homePlayerRow['player_id']);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anriëtte Myburgh
  • 13,347
  • 11
  • 51
  • 72
  • If you're only accessing the associative keys (player_id) then it's best to use `mysql_fetch_assoc`. You could also use `mysql_fetch_row` then `$homePlayerRow[0]`, which is slightly faster. – DisgruntledGoat Jul 08 '09 at 17:11

2 Answers2

29

It depends...

Documentation 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."

Source: http://us2.php.net/array_push

So it boils down to how much data you want to cram into that array at any particular moment.

Additionally, there's a fall-back. If the array-referenced doesn't exist when you call it using array_push, you'll bump an error. If you use $array[], the array will be created for you.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • In the end I decided to go with array[] = ... as the array might become very large at some stage – Anriëtte Myburgh Jul 02 '09 at 14:10
  • 2
    I believe it's faster to declare an array (with `$arr = array()`) before using `$arr[] = X`. It's also useful if your `$arr[]` statements are inside some control logic - you still have a variable at the end, an array with no elements. – DisgruntledGoat Jul 08 '09 at 17:07
  • @DisgruntledGoat why is it faster to declare an empty array? Do you have proof of this? – Kosi Apr 24 '19 at 17:43
21

You can run it and see that array_push is slower in some cases:

http://snipplr.com/view/759/speed-test-arraypush-vs-array/

Run your code. Enjoy.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223