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

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see