Mistake 2: Forgetting to unset the reference variable after the loop.

In the previous blog of the series we started with the isset function mistake and I have promised to post about the next mistake which is leaving dangling array references after foreach loop.

While working with arrays, we need foreach to iterate over arrays. In some case, we might be just displaying each array element while iterations but in some case, we might need to manipulate or operate on each element. When there is a case, where we need to operate on each element, using references in foreach loops can be useful. See below code snippet.

$cities = array(‘Amritsar’, ‘Delhi’, ‘Pune’, ‘Banglore’);
foreach ($cities as &$value) {
   $value = $value + ‘ Is In India’;
}
// $cities is now array(‘Amritsar Is In India’, ‘Delhi Is In India’, ‘Pune Is In India’, ‘Banglore Is In India’)

What is the issue in this then?

What will that cause If I forget to unset the reference?

<?php

$cities = array('Amritsar', 'Delhi', 'Pune', 'Banglore');

foreach ($cities as &$value) {

   // Operations

}

echo "<br>Cities After First Loop";

print_r($cities);

$countries = array('India','Bhutan','Nepal','China');

foreach ($countries as $value) {

   // Operations

}

echo "<br>Cities After Second Loop";

print_r($cities);

?>

Expected output cities array : ([0]= >Amritsar, [1]=>Delhi, [2]=>Pune, [3]=>Banglore);

Actual output cities array : ( [0] => Amritsar [1] => Delhi [2] => Pune [3] => China )

 

What happened here? So when the second loop executed $value is reference, Because it is used as reference in first loop, Hence when second loop is iterating the original reference is overwritten.

So If you are using reference in foreach loop don’t forgot to unset the reference variable right after foreach loop ends. See below code snippet.

 

<?php

$cities = array('Amritsar', 'Delhi', 'Pune', 'Banglore');

foreach ($cities as &$value) {

   // Operations

}

unset($value); //  $value no longer references $cities[3]

echo "<br>Cities After First Loop";

print_r($cities);

$countries = array('India','Bhutan','Nepal','China');

foreach ($countries as $value) {

   // Operations

}

echo "<br>Cities After Second Loop";

print_r($cities);

?>

Output :

Cities After First Loop = Array ( [0] => Amritsar [1] => Delhi [2] => Pune [3] => Banglore )

Cities After Second Loop = Array ( [0] => Amritsar [1] => Delhi [2] => Pune [3] => Banglore )

In the next article, we will try to discuss the mistakes that we do while performing SQL queries inside loops. I hope you will not repeat the mistake of forgetting to unset references after foreach loop as you know now what can be caused further.  Keep doing new mistakes and stay tuned for next mistake with their solutions.