I know this post is old, but I think this info is very important:
You asked:
Is it necessary to unset($value), when $value remains after foreach
loop, is it good practice?
It depends on wheter you iterate by value or by reference.
First case (by value):
$array = array(1, 2, 3, 4);
foreach ($array as $value) {
//here $value is 1, then 2, then 3, then 4
}
//here $value will continue having a value of 4
//but if you change it, nothing happens with your array
$value = 'boom!';
//your array doesn't change.
So it's not necessary to unset $value
Second case (by reference):
$array = array(1, 2, 3, 4);
foreach ($array as &$value) {
//here $value is not a number, but a REFERENCE.
//that means, it will NOT be 1, then 2, then 3, then 4
//$value will be $array[0], then $array[1], etc
}
//here $value it's not 4, it's $array[3], it will remain as a reference
//so, if you change $value, $array[3] will change
$value = 'boom!'; //this will do: $array[3] = 'boom';
print_r ($array); //Array ( [0] => 1 [1] => 2 [2] => 3 [3] => boom! )
So in this case it is a good practice to unset $value, because by doing that, you break the reference to the array. Is it necessary? No, but if you don't do it, you should be very careful.
It can lead to unexpected results like this one:
$letters = array('a', 'b', 'c', 'd');
foreach ($letters as &$item) {}
foreach ($letters as $item) {}
print_r ($letters); //output: Array ( [0] => a [1] => b [2] => c [3] => c )
// [a,b,c,c], not [a,b,c,d]
This is also valid for PHP 7.0
Same code with unset:
$letters = array('a', 'b', 'c', 'd');
foreach ($letters as &$item) {}
unset ($item);
foreach ($letters as $item) {}
print_r ($letters); //output: Array ( [0] => a [1] => b [2] => c [3] => d )
// now it's [a,b,c,d]
I hope this can be useful for someone in the future. :)