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

随声附和 提交于 2019-12-17 10:57:50

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/1074059/array-push-vs-array-which-is-fastest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!