在 PHP 中迭代数组的最快方法 [英] Fastest way to iterate array in PHP

查看:29
本文介绍了在 PHP 中迭代数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Zend PHP 认证.

I'm studying for the Zend PHP certification.

不确定这个问题的答案.

Not sure the answer to this question.

问题:使用 PHP 5 迭代和修改数组的每个元素的最佳方法是什么?

a) 您不能在迭代期间修改数组

a) You cannot modify an array during iteration

b) for($i = 0; $i

c) foreach($array as $key => &$val) {/* ... */}

d) foreach($array as $key => $val) {/* ... */}

e) while(list($key, $val) = each($array)) {/* ... */}

<小时>

我的直觉是 (B) 因为不需要创建临时变量然后我意识到它不适用于关联数组.在网上进一步搜索发现:将不变数组计数存储在单独的变量中可提高性能.


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++) { }

推荐答案

从这些选项来看,C 将是显而易见的答案.

From these options C would be the obvious answer.

其余选项(除 A 外) 可用于实现这一点,具体取决于括号内的代码,但问题并未显示该代码.所以一定是C.

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.

并且您回答了错误的问题 - 在 for 循环之前执行 count() 会提高性能,但这个问题与性能无关.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆