views:

331

answers:

2

Hi all

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']);
}

Thanks in advance

+10  A: 

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.

Jonathan Sampson
In the end I decided to go with array[] = ... as the array might become very large at some stage
Anriëtte Combrink
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
+4  A: 

u can run and see that array_push is slower in some case

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

run your code . enjoy

Haim Evgi
Link at top of snipplr points to viagra ...? Wanted to give you upvote but not anymore. Maybe you aren't even to blame.
Alfred
Sorry I did not notice, I am a religious person
Haim Evgi
Just tested that link and it's correct, no viagra pointing now. :)
Anriëtte Combrink