Today I was asked a question regarding PHP’s foreach statement: If the array through wich a script iterates is generated by a function, how often is this function called? In this example, will getArray() be called only once or three times?
$c = 0;
function getArray()
{
global $c;
echo (++$c) . ". call to " . __FUNCTION__ . "\n";
return array(1, 2, 3);
}
foreach (getArray() as $e)
{
echo "ForEach: " . $e . "\n";
}
I didn’t know the answer myself, although I presumed the function gets called only once. Interestingly, the PHP Manual doesn’t say a word about this question.
So, what’s the answer? The function gets called only once, as I suspected. Here’s the output of the code above:
1. call to getArray ForEach: 1 ForEach: 2 ForEach: 3