CodeIgniter Forums
foreach array evaluation - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: foreach array evaluation (/showthread.php?tid=23211)



foreach array evaluation - El Forum - 10-03-2009

[eluser]crikey[/eluser]
Hi guys,

Just wondering how often the 'array_expression' is evaluated in a foreach loop. I have a model function ('get_tags') returning an array of objects from an active record query. I want to produce an array where each index is the 'id' property and the value is the 'name' property of each object. Here's my loop:

Code:
$user_tags = array();
foreach ($this->Users_model->get_tags() as $tag)
{
    $user_tags[$tag->id] = $tag->name;
}

I'm just wondering if the array in the loop is evaluated only once, and that 'temporary' array used on each subsequent iteration, or if it's evaluated each iteration. If its the latter, I guess I should assign the 'get_tags' result to a variable and iterate using that (for better performance)?

Thanks
Grant


foreach array evaluation - El Forum - 10-04-2009

[eluser]bitist[/eluser]
The get_tags() in the foreach is evaluated only once.