关于PHP中向数组添加元素的操作
大家好。
我知道一些在 PHP 中向数组添加元素的方法。
$anArray[] = $newElement;
<-我喜欢这个
array_push()
<-我见过很多人使用它。
我确信还有其他人。
我想知道其中哪一个更有效,或者是否有其他更有效的方法。
注意:我只想添加一个元素,可以在数组的末尾。我的意思是我不会指定新元素要添加到什么位置。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
赋值运算符会稍微快一些[不需要执行函数调用],但是使用 array_push(),您可以一次附加多个变量。
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.没有一个比其他的更有效率。
PHP 是一种高级语言,在大多数情况下,像这样的简单等效操作会生成完全相同的操作码。
在极少数情况下,生成的低级代码存在差异,其速度如此之快,以至于尝试操纵它们将被视为微优化。
总之,不用担心。编写 PHP 代码,按照它所说的那样做,你就会没事的。
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.
实际上,这取决于您想要实现的目标。只是向数组添加一个值,而不考虑数组键,还是数组键必须是特定的?您建议的第一种方法允许您为值分配自定义键,
array_push()
将简单地分配一个比前一个大一的数字键。另外,array_push() 允许您一次向数组添加多个值,如下所示:
您可以对第一个方法执行相同的操作,这只是大量的重复。 :)
如果键不重要,或者只需要添加一个值,那么我只想说这是一个意见问题。
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: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.