0

Possible Duplicate:
How is an array in a PHP foreach loop read?

If I have this function:

function getList()
{
   $list = array();
   $list['foo'] = 'Foo';
   $list['bar'] = 'Bar';
   return $list;
}

And then I do this:

foreach ( getList() as $item )
{
     echo $item.'<br>';
}

Will that code be slower than doing this:

$list = getList();
foreach ( $list as $item )
{
     echo $item.'<br>';
}
Community
  • 1
  • 1
Ali
  • 261,656
  • 265
  • 575
  • 769
  • 5
    Usually when I write a question like this I realize before I click "submit" that I would have spent less time profiling it for myself :) –  May 08 '12 at 04:48
  • The two solution should have roughly the same running time. I've not tested them as I would do I will have a benchmark for the php version I'm using. In similar case, though, I would use the second solution as does not leave room to similar doubts – Eineki May 08 '12 at 05:03

2 Answers2

5

I'm sure that in your first example, the getList() function inside foreach is only evaluated once. Thus, there wouldn't be any huge difference.

Update: As requested, this was a quick test I did in php interactive mode.

function getList() {
    echo 'a';
    return array(1,2,3);
}

foreach(getList() AS $item) {
    echo $item;
}

Result: a123

wyred
  • 574
  • 6
  • 23
  • It would be nice to have some justification behind your answer. "I'm sure" doesn't really cut it. – nickb May 08 '12 at 04:52
  • @nickb: Putting an echo into `getList()` does cut it though. Though I agree, he should probably mention that in the original answer. – ccKep May 08 '12 at 04:54
  • Thanks for the suggestion. I've put up the test code that I just did to back up my answer. – wyred May 08 '12 at 04:57
2

Try this

<?php
function getList()
{
    echo '<div>getList()</div>';
    $list = array();
    $list['foo'] = 'Foo';
    $list['bar'] = 'Bar';
    return $list;
}

foreach ( getList() as $item )
{
    echo $item.'<br>';
}
?>

And you only will get 1 echo, which means getList() only called once :)

Sempa
  • 308
  • 2
  • 8