Search code examples
phpmysqlmicro-optimization

array_push() vs. $array[] = .... Which is fastest?


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

Solution

  • 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.