Question: We have all heard of how in a `for` loop, we should do this:

```
for ($i = 0, $count = count($array); $i < $c; ++$i)
{
    // Do stuff while traversing array
}

```

instead of this:

```
for ($i = 0; $i < count($array); ++$i)
{
    // Do stuff while traversing array
}

```

for performance reasons (i.e. initializing `$count` would've called `count()` only once, instead of calling `count()` with every conditional check).

Does it then also make a difference if, in a `foreach` loop, I do this:

```
$array = do_something_that_returns_an_array();

foreach ($array as $key => $val)
{
    // Do stuff while traversing array
}

```

instead of this:

```
foreach (do_something_that_returns_an_array() as $key => $val)
{
    // Do stuff while traversing array
}

```

assuming circumstances allow me to use either? That is, does PHP call the function only once in both cases, or is it like `for` where the second case would call the function again and again?

Answer: 
I think testing it will surely answer that. 

Here is my code:

```
function GetArray() {
    echo "I am called.\n";
    return array("One"=>1, "Two"=>2, "Three"=>3, "Four"=>4, "Five"=>5);
}

echo "Case #1\n";
$array = GetArray();
foreach ($array as $key => $val){
    // Do stuff while traversing array
    echo "    Inside the loop: $key => $val\n";
}
echo "\n";

echo "Case #2\n";
foreach (GetArray() as $key => $val) {
    // Do stuff while traversing array
    echo "    Inside the loop: $key => $val\n";
}
echo "\n";

```

and here is the result:

```

Case #1
I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5

Case #2
I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5

```

They both read call function once. So no different.
I would set up an example to see what happens. Something like...

```
function do_something_that_returns_an_array() {
    echo 'I have been called!'; 
    return array('i am an', 'array');
}

```

[As you can see on CodePad, it is only being called once](http://codepad.org/3nHcgaCm).