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.
In your first example:
$myVariableis 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:
$myVariableis 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
$myArrayis empty (count($myArray) === 0)$myVariablewill not be created in your first example, but in your second it will with a value of null.