How often are functions returning an array for PHP’s foreach statement called?

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

Über Stefan

Polyglot Clean Code Developer

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert