Jiew Meng
Jiew Meng

Reputation: 88197

Question foreach on arrays returned by functions

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 will be better to use

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

Upvotes: 1

Views: 70

Answers (1)

cletus
cletus

Reputation: 625057

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

Upvotes: 7

Related Questions