什么更有效?在foreach
循环中放置函数...
$array = array(1, 2, 3, 4, 5);
foreach (array_keys($array) as $key) {
# do whatever...
}
或者在变量之前指定:
$array = array(1, 2, 3, 4, 5);
$keys = array_keys($array);
foreach ($keys as $key) {
# do whatever...
}
答案 0 :(得分:0)
无论哪个看起来更具可读性......虽然后者会比前者使用更多的内存:但在这种情况下都不需要,因为你可以做到:
$array = array(1, 2, 3, 4, 5);
foreach ($array as $key => $value) {
# do whatever...
}
如果你只需要密钥,你可以使用上面的内容而忽略该值(虽然在语法上你需要指定它)
修改强>
如果您关注性能和内存使用情况,请使用256k元素的数组进行快速测试(足以在统计数据中给出差异):
foreach (array_keys($array) as $key) {
}
给出
Call time was 0.0466 seconds
Current memory usage: 21.75 MB
Peak memory usage: 42.75 MB
$keys = array_keys($array);
foreach ($keys as $key) {
}
给出
Call time was 0.0335 seconds
Current memory usage: 42.75 MB
Peak memory usage: 42.75 MB
foreach ($array as $key => $value) {
}
给出
Call time was 0.0103 seconds
Current memory usage: 21.5 MB
Peak memory usage: 21.5 MB