15

If I declare a variable inside a foreach loop, such as:

foreach($myArray as $myData) {
    $myVariable = 'x';
}

Does PHP destroy it, and re-creates it at each iteration ? In other words, would it be smarter performance-wise to do:

$myVariable;
foreach($myArray as $myData) {
    $myVariable = 'x';
}

Thank you in advance for your insights.

4
  • may be like global and local variable Commented Nov 29, 2012 at 13:24
  • 3
    No, it doesn't; and the variable still exists outside of the loop bafter you have finished iterating. It is only "destroyed" when you exit the function where the loop is defined.... even your $myData variable will still exist after the loop has finished, holding the value of the last element in $myData.... this can be particularly tricky if you've used it by reference Commented Nov 29, 2012 at 13:31
  • 1
    Variable can be _destroyed by unsetting it. Commented Nov 29, 2012 at 13:31
  • Variables in PHP are neither destroyed nor created. They might be undefined, but that won't PHP prevent to use them. Also the common rules of scope apply, and foreach is nothing special here. Commented Nov 29, 2012 at 16:02

4 Answers 4

24

In your first example:

foreach($myArray as $myData) {
    $myVariable = 'x';
}

$myVariable is created during the first iteration and than overwritten on each further iteration. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

In your second example:

$myVariable;
foreach($myArray as $myData) {
    $myVariable = 'x';
}

$myVariable is created before any iteration and set to null. During each iteration if will be overwritten. It will not be destroyed at any time before leaving the scope of your script, function, method, ...

Update

I missed to mention the main difference. If $myArray is empty (count($myArray) === 0) $myVariable will not be created in your first example, but in your second it will with a value of null.

Sign up to request clarification or add additional context in comments.

6 Comments

both of your examples are basically the same. Wether you declare a variable before the loop or in the loop, the variable will have the value it had at the end of the last iteration. The variable will not be destroyed after the foreach loop, even if you didn't declare it before the loop. This is something typical for PHP and doesn't happen in most other programming languages.
In addition, if you do need to destroy a variable from within a loop like this you can use unset(): php.net/manual/en/function.unset.php
@Jules These are not my examples, these are the examples from the question!
@eisberg: Undefined variables in PHP have always the value of NULL. You should explain why this should be special with foreach because it is not.
@hakre I am (like everyone of us should) programming in error_reporting(-1); (yes all the time) and uninitialized variables give errors and are just plain wrong.
|
2

According to the debugger in my IDE (NuSphere PHPed) in your first example:

foreach($myArray as $myData) {
    $myVariable = 'x';
}

$myVariable is only created once.

Comments

2

According to my experiment, it's the same:

<?php
for($i = 0; $i < 3; $i++) {
    $myVariable = $i;
}
var_dump($myVariable);

prints: int(2)

<?php
$myVariable;
for($i = 0; $i < 3; $i++) {
    $myVariable = $i;
}
var_dump($myVariable);

prints: int(2)

5 Comments

The first one would throw an error if it hadn't been assigned to in the for loop, whereas the second one wouldn't.
@diggersworld Surprisingly, it doesn't throw an error (notice) for me. Does it for you?
ah, no it doesn't, sorry. I thought it would have. That's interesting.
@diggersworld @user4035 Perhaps you don't have all errors turned on? When I ran the first snippet with for($i = 0; $i < 0; $i++) it generated the error 'Notice: Undefined variable: myVariable in - on line 6' as expected.
@AmadeusDrZaius Yes, I didn't have notices turned on. PHP will define this variable on the fly.
1

The problem is $myVariable is not truly local to foreach only. So it can clobber a global variable under the same name.

A way around that is make your foreach an inline anonymous function.

E.g.

$myforeach=function(&$myArray){ // pass by ref only if modifying it
  foreach($myArray as $myData) {
    $myVariable = 'x';
  }
};
$myforeach($myArray);  // execute anonymous.

This way you guarantee it will not step on other globals.

1 Comment

This good way to keep the global vars intact have same var names used in foreach loops. Good work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.