关于PHP中向数组添加元素的操作

发布于 2024-11-08 23:24:15 字数 478 浏览 0 评论 0原文

可能的重复:
Php array_push() 与 myArray[]

大家好。

我知道一些在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伴我老 2024-11-15 23:24:15

赋值运算符会稍微快一些[不需要执行函数调用],但是使用 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.

庆幸我还是我 2024-11-15 23:24:15

没有一个比其他的更有效率。

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.

死开点丶别碍眼 2024-11-15 23:24:15

实际上,这取决于您想要实现的目标。只是向数组添加一个值,而不考虑数组键,还是数组键必须是特定的?您建议的第一种方法允许您为值分配自定义键,array_push() 将简单地分配一个比前一个大一的数字键。

另外,array_push() 允许您一次向数组添加多个值,如下所示:

array_push($myArray, "value1", "value2", "value3");

您可以对第一个方法执行相同的操作,这只是大量的重复。 :)

如果键不重要,或者只需要添加一个值,那么我只想说这是一个意见问题。

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:

array_push($myArray, "value1", "value2", "value3");

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文