title: How is an array in a PHP foreach loop read?
body: <p>We have all heard of how in a <code>for</code> loop, we should do this:</p>
  
  <pre><code>for ($i = 0, $count = count($array); $i &lt; $c; ++$i)
  {
      // Do stuff while traversing array
  }
  </code></pre>
  
  <p>instead of this:</p>
  
  <pre><code>for ($i = 0; $i &lt; count($array); ++$i)
  {
      // Do stuff while traversing array
  }
  </code></pre>
  
  <p>for performance reasons (i.e. initializing <code>$count</code> would've called <code>count()</code> only once, instead of calling <code>count()</code> with every conditional check).</p>
  
  <p>Does it then also make a difference if, in a <code>foreach</code> loop, I do this:</p>
  
  <pre><code>$array = do_something_that_returns_an_array();
  
  foreach ($array as $key =&gt; $val)
  {
      // Do stuff while traversing array
  }
  </code></pre>
  
  <p>instead of this:</p>
  
  <pre><code>foreach (do_something_that_returns_an_array() as $key =&gt; $val)
  {
      // Do stuff while traversing array
  }
  </code></pre>
  
  <p>assuming circumstances allow me to use either? That is, does PHP call the function only once in both cases, or is it like <code>for</code> where the second case would call the function again and again?</p>