Jump to content

question about variable scope and unset in a foreach loop


darth_tater

Recommended Posts

This is more of a technical question that i could not find the answer to pn the php.net manual pages.

 

take the folowing example code:

 


foreach ($array as $key => $value){

$tempvariable = some_property_of($value);

}

unset($tempvariable);

 

is that unset statement needed?  Does PHP automatically destroy the variables once the foreach loop is left?

 

 

Link to comment
Share on other sites

PHP has a garbage collector that will look at stuff once it's left scope. However there are only three scopes in PHP: "global" scope, class scope, and function scope. Constructs like foreach don't have scope - when execution leaves it, any variables declared inside are still accessible (and in scope) and thus won't be destroyed.

 

In general, you don't need to worry about unset()ing variables. In general, PHP scripts run in a matter of milliseconds, and once they end PHP will clean up everything automatically.

Link to comment
Share on other sites

Ok, thanks!  Thats exactly the answer i was looking for.

 

 

And i'll be using unset for:

 

1) security - you cant read or access or write a variable that no longer exists.

2) conservation - Lets not waste ram if we don't have to.

 

 

i am actively developing a web app that could end up using 20+ classes for the most complex pages....  Any optimization i can do as i am writing these functions / classes i'll need later down the road!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.