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've always assumed that `do_something_that_returns_an_array()` only runs once because, unlike in the for loop, there's no reason for it to run multiple times. The reason the for loop truth checker runs at the end of every iteration is to allow for very complicated checkers.

As a test, I did the following:

```
function get_array() {echo 5; return array(1,2,3,4,5);}
foreach(get_array() as $key => $value) {}

```

The script printed 5 once. Therefore, the function `get_array()` only evaluates once.
foreach() works with Iterator or IteratorAggregate objects (e.g., arrays and objects implementing the interface). It can't work with **immutable** objects. Functions return **immutable** objects, so the returning array have to be copied into Iterator object before foreaching (it's made by php itself)