在 PHP 中迭代数组的最快方法
我正在学习 Zend PHP 认证。
我不确定这个问题的答案。
问题:使用 PHP 5 迭代和修改数组的每个元素的最佳方法是什么?
a) 迭代期间不能修改数组
b)
for($i = 0; $i < count($array); $i++) { /* ... */ }
c)
foreach($array as $key => &$val) { /* ... */ }
d)
foreach($array as $key => $val) { /* ... */ }
e)
while(list($key, $val) = every($array)) { /* ... */ }
我的本能是 (B),因为不需要创建临时变量,但后来我意识到它不适用于关联数组。
在互联网上进一步搜索,我发现了这一点:
将不变数组计数存储在单独的变量中可以提高性能。
$cnt = count($array);
for ($i = 0; $i < $cnt; $i++) { }
I'm studying for the Zend PHP certification.
I am not sure about the answer to this question.
Question: What is the best way to iterate and modify every element of an array using PHP 5?
a) You cannot modify an array during iteration
b)
for($i = 0; $i < count($array); $i++) { /* ... */ }
c)
foreach($array as $key => &$val) { /* ... */ }
d)
foreach($array as $key => $val) { /* ... */ }
e)
while(list($key, $val) = each($array)) { /* ... */ }
My instinctive is (B) since there is no need to create a temporary variable, but then I realize it won't work for associative arrays.
Further searching around the Internet I found this:
Storing the invariant array count in a separate variable improves performance.
$cnt = count($array);
for ($i = 0; $i < $cnt; $i++) { }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从这些选项中,C 是显而易见的答案。
其余选项(除了 A)可以用于实现该目的,具体取决于括号内的代码,但问题不显示该代码。所以它一定是 C。
而且你回答了错误的问题 - 是的,在 for 循环之前执行 count() 会提高性能,但这个问题与性能无关。
From these options, C would be the obvious answer.
The remaining options (besides A) may be used to achieve that, depending on the code inside the parenthesis, but the question does not show that code. So it must be C.
And you are answering the wrong question - yes, doing count() before the for cycle will improve performance, but this question is not about performance.
您可以使用任何所示的构造来迭代和修改数组的每个元素。但有一些注意事项:
b) 仅当数组是键为 0 到 n-1 的数字数组时才有用。
c) 对于两种数组都很有用。另外,
$value
是元素值的引用。因此,在foreach
内更改$value
也会更改原始值价值。d) 与 c) 类似,但
$value
是值的副本(请注意,foreach
对$array
的副本进行操作)。但通过元素的键,您可以使用$array[$key]
访问和更改原始值。e) 与 d) 类似。使用
$array[$key]
访问和更改原始元素。You can iterate and modify every element of an array with any of the shown constructs. But some notes on that:
b) Is only useful if the array is a numeric array with the keys from 0 to n-1.
c) Is useful for both kinds of arrays. Additionally
$value
is a reference of the element’s value. So changing$value
insideforeach
will also change the original value.d) Like c) except
$value
is a copy of the value (note thatforeach
operates on a copy of$array
). But with the key of the element you can access and change the original value with$array[$key]
.e) Like d). Use
$array[$key]
to access and change the original element.SPL 将是这里的最佳答案。
SPL would be the best answer here.