开发者

Question foreach on arrays returned by functions

开发者 https://www.devze.com 2023-01-08 14:00 出处:网络
i wonder if i do foreach (func_to_return_array() as $item) { ... } will it call func_to_return_array() many times (the array length)? if it does i guess it w开发者_StackOverflowill be better to use

i wonder if i do

foreach (func_to_return_array() as $item) { ... }

will it call func_to_return_array() many times (the array length)? if it does i guess it w开发者_StackOverflowill be better to use

$arr = func_to_return_array();
foreach ($arr as $item) { ... }


It will only call func_to_return_array() once. Example:

foreach (foo() as $v) {
  echo "$v\n";
}

function foo() {
  echo "Called foo\n";
  return range(1, 5);
}

Output:

Called foo
1
2
3
4
5
0

精彩评论

暂无评论...
验证码 换一张
取 消