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?

  1. $c = 0;
  2. function getArray()
  3. {
  4.         global $c;
  5.         echo (++$c) . ". call to " . __FUNCTION__ . "\n";
  6.         return array(1, 2, 3);
  7. }
  9. foreach (getArray() as $e)
  10. {
  11.         echo "ForEach: " . $e . "\n";
  12. }

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 uns 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