Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are PHP variables declared inside a foreach loop destroyed and re-created at each iteration?

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.

like image 363
Alexandre Bourlier Avatar asked Nov 29 '12 13:11

Alexandre Bourlier


People also ask

How does the foreach loop work in PHP?

PHP foreach loop is utilized for looping through the values of an array. It loops over the array, and each value for the fresh array element is assigned to value, and the array pointer is progressed by one to go the following element in the array.

Does continue work in foreach PHP?

Introduction. The continue statement is one of the looping control keywords in PHP. When program flow comes across continue inside a loop, rest of the statements in current iteration of loop are skipped and next iteration of loop starts. It can appear inside while, do while, for as well as foreach loop.

Which is faster foreach or for loop in PHP?

The foreach loop is considered to be much better in performance to that of the generic for loop. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.


2 Answers

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.

like image 168
eisberg Avatar answered Oct 22 '22 15:10

eisberg


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

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

$myVariable is only created once.

like image 31
WhoaItsAFactorial Avatar answered Oct 22 '22 16:10

WhoaItsAFactorial