Re: foreach and destroying variables for memory saving

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Tim | iHostNZ wrote:
> Hi All,
> 
> Just to annoy the hell out of you, another thing that has been on my mind
> for a while:
> 
> I love the foreach ($ar as $k => $v) { ... } construct and use it all the
> time. However, I read somewhere that foreach actually uses a copy of $ar
> instead of the array itself by reference. Wouldn't it be much more
> usefull/efficient, if foreach would use the array by reference? Then one
> could change arrays while iterating over them (without having to use the old
> fashioned for ($i=0; $i<count($ar); $i++), also this doesnt work for
> associative arrays). I know you can do it with while and list somehow, but i
> personally find that language construct rather ugly and can never remember
> it. Is there another way that any of you use? Please enlighten me.
> I just use foreach because its easy, but it might not be the best. However,
> it seems to perform good enough for what i've done so far.
You can use:
$arr = array('abc'=>'123','ver'=>phpversion());
foreach ($arr as $key=>&$val) {
    echo $val."\n";
    // Beware! - Changing $val will change it in $arr
}

// or like this:

$arr = array('abc'=>'123','ver'=>phpversion());
reset($arr);
while (list($key, $val) = each($arr)) {
    echo $val."\n";
}


> 
> Somewhere i also read that one can save a lot of memory by destroying
> variables. Is that done with unset, setting it to null or something similar?
> So, i take there is no garbage collection in php? I've never actually looked
> at the c source code of php. Maybe its time to actually do that. But it
> might be easier if someone can answer this from the top of their head.
> 
> Thanks for your patience.
> 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux