遍历在PHP数组的最快方法 [英] Fastest way to iterate array in PHP
问题描述
我学习了Zend的PHP认证。
不知道这个问题的答案。
问:什么是迭代和修改使用PHP 5数组中的每个元素的最佳方法
一)迭代过程中不能修改一个数组
B)
为($ i = 0; $ I<计数($数组); $ I ++){/ * ... * /}
C)
的foreach($数组$关键=>&安培; $ VAL){/ * ... * /}
D)
的foreach($数组$关键=> $ VAL){/ * ... * /}
E)
而(名单($键,$ VAL)=每($阵列)){/ * ... * /}
块引用>
我的本能是(B),因为没有必要创建临时变量,然后我意识到它不会对关联数组。进一步搜索周围的网发现这一点:
存储阵列不变计算一个单独的变量可以提高性能。$ CNT =计数($数组);
为($ I = 0; $ I< $ CNT; $ I ++){}
解决方案从这些选项C.将很明显的答案。
剩下的选项(除了A)的可以的用于实现这一目标,根据括号内的code,但问题并没有显示code。因此,它必须是C。
而你回答错了问题 - 是做之前的周期数()将提高性能,但这个问题不是性能
。I'm studying for the Zend PHP certification.
Not sure 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 temporary variable then I realize it won't work for associative arrays. Further searching around the net found this: Storing the invariant array count in a separate variable improves performance.
$cnt = count($array); for ($i = 0; $i < $cnt; $i++) { }
解决方案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.
这篇关于遍历在PHP数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!