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

28,422

Solution 1

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.

Solution 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)

Solution 3

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

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

$myVariable is only created once.

Share:
28,422
Alexandre Bourlier
Author by

Alexandre Bourlier

Software: Wordpress Drupal MediaWiki Grails Backbone JS Languages: PHP Groovy Java JQuery Javascript MySQL

Updated on September 27, 2020

Comments

  • Alexandre Bourlier
    Alexandre Bourlier over 3 years

    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.