foreach($images as $key => $image)
{
    if(in_array($image, array(
       'http://i27.tinypic.com/29ykt1f.gif',
       'http://img3.abload.de/img/10nxjl0fhco.gif',
       'http://i42.tinypic.com/9pp2tx.gif',
    ))
    {
        unset($images[$key]);
    }
}
Answer from hsz on Stack Overflow
🌐
Kitson-consulting
kitson-consulting.co.uk › blog › call-unset-after-php-foreach-loop-values-passed-reference
Call unset() after a PHP foreach loop with values passed by reference | Kitson Consulting
My intuition strongly suggests ... Wily behave as outlined above. Anyway, the short version is that you can avoid this by adding unset( $value ); immediately after the first foreach....
🌐
SitePoint
sitepoint.com › php
Is it a good idea to use unset inside a foreach? - PHP - SitePoint Forums | Web Development & Design Community
March 6, 2016 - I did something similar to this: foreach($model->get('data', array()) as $element) { foreach($element['user_info'] as $key => $value) { if(in_array('admin', $value) { unset…
🌐
PHP
php.net › manual › en › control-structures.foreach.php
PHP: foreach - Manual
It is possible to directly modify array elements within a loop by preceding $value with &. In that case the value will be assigned by reference. <?php $arr = [1, 2, 3, 4]; foreach ($arr as &$value) { $value = $value * 2; } // $arr is now [2, 4, 6, 8] unset($value); // break the reference with the last element ?>
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-remove-an-array-element-in-a-foreach-loop
How to remove an array element in a foreach loop? - GeeksforGeeks
July 11, 2025 - This can be tricky because modifying the array's length during iteration can lead to unexpected behavior or skipped elements. Use unset() function to remove array elements in for each loop.
🌐
SitePoint
sitepoint.com › php
Using unset with foreach - PHP - SitePoint Forums | Web Development & Design Community
August 12, 2010 - Okay, so I’m not entirely a n00b, ...s.foreach.php · and it mentioned using unset to destroy remaining references: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). I’ve haven’t seen any of the developers where I work do this. Is it necessary? What is the purpose of doing this? Here’s my code: (im basically populating a table with data held in an array from ...
🌐
GitHub
github.com › php › php-src › issues › 13178
Foreach loop with value by reference and using `unset` and set to array creates overflow memory. · Issue #13178 · php/php-src
January 17, 2024 - $array = [ new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), new stdClass(), ]; foreach ($array as $key => &$value) { unset($array[$key]); $array[] = $value;// the same situation with $array[$key] = $value; }
Published   Jan 17, 2024
Find elsewhere
Top answer
1 of 4
38

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. :)

2 of 4
4

There's no need to use unset in the current context that you are using it. unset will simply destroy the variable and its content.

In the example you are giving, this is looping through an array creating $value, then you are unsetting that variable. Which means it no longer exists in that code. So that does absolutely nothing.

To visuallize what I am talking about look at this example:

$value = 'Hello World';
echo $value;
unset($value);
echo $value;

The following out will be:

Hello World<br /><b>NOTICE</b> Undefined variable: value on line number 6<br />

So you will first see the Hello World, but after unsetting that variable trying to call it will just cause an error.

To answer your question, you really don't have to unset value; there's no need for it. As the foreach loop is setting a $value of each array() + 10.

Unsetting it will cause the work to be removed, and forgotten.

🌐
PHP
wiki.php.net › rfc › foreach_unwrap_ref
PHP: rfc:foreach_unwrap_ref
$tmp =& $value; unset($value); // Unset has reference breaking semantics. $value = $tmp; For the motivating case, this means that $value is no longer a reference after the first loop, which means that the second loop will not modify the array: $array = [1, 2, 3]; foreach ($array as &$value) ...
🌐
SonarSource
rules.sonarsource.com › php › rspec-4824
References used in "foreach" loops should be "unset"
Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your PHP code
🌐
Reddit
reddit.com › r/php › after 10 years of using php, i just learned that bad things can happen if you don't unset() the reference variable after a foreach (see #1).
r/PHP on Reddit: After 10 years of using PHP, I just learned that bad things can happen if you don't unset() the reference variable after a foreach (see #1).
May 25, 2015 - It's also mentioned in the PHP manual, but how many of us have reach the PHP manual page for foreach recently? I never realized this could happen until I spent today struggling with a strange bug caused by this. I really think the next major update of PHP should unset the loop variable after foreach loops.
🌐
SonarSource
rules.sonarsource.com › php › type › bug › rspec-4824
Bug: References used in "foreach" loops should be "unset"
Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your PHP code