Is it true that unsetting variables doesn't actually decrease the memory consumption during runtime?

Yep. From PHP.net:

unset() does just what it's name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

If you are doing $whatever = null; then you are rewriting variable's data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.

Regarding your other question:

And is there any reason to unset variables apart from destroying session varaibles for instance or for scoping?

Not really, you pretty much summed it.

Answer from Aron Rotteveel on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.unset.php
PHP: unset - Manual
If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_var_unset.asp
PHP unset() Function
<?php $a = "Hello world!"; echo "The value of variable 'a' before unset: " . $a . "<br>"; unset($a); echo "The value of variable 'a' after unset: " .
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-php-unset-function
What is the PHP unset() function?
The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use ๏ผ„GLOBALS array to do so.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ php-unset-function
PHP | unset() Function - GeeksforGeeks
April 9, 2025 - In PHP, the unset() function is used to destroy a variable, array element, or object. Once a variable or array element is "unset", it is completely removed from memory, and it no longer exists in the program.
๐ŸŒ
w3resource
w3resource.com โ€บ php โ€บ function-reference โ€บ unset.php
PHP unset() function - w3resource
The unset() function destroys a given variable. ... No value is returned. ... <?php $xyz='w3resource.com'; echo 'Before using unset() the value of $xys is : '. $xyz.'<br>'; unset($xyz); echo 'After using unset() the value of $xys is : '. $xyz; ?>
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ home โ€บ php โ€บ php unset function
PHP unset Function
May 26, 2007 - The PHP Variable Handling unset() function is used to to delete a variable. Unsetting a variable deletes it from memory and prevents it from being used again. If you use an unset variable, it will have no value.
๐ŸŒ
Reddit
reddit.com โ€บ r/php โ€บ do you guys ever unset() your php variables?
r/PHP on Reddit: Do you guys ever unset() your PHP variables?
February 22, 2012 -

Hey all, I'm trying to learn as much as I can about PHP and the best programming practices for it. I never use PHP's unset() function to unset a variable, because I've never learned if I should or not. Is it generally recommended to unset all variables when they are done use? Do you use unset() in your projects?

I currently use a MVC framework (CodeIgniter) so I guess it would depend on the specific variable about where would be the best place to unset them. Some would be unset in the views, some in the controllers, some in the models.

Any insight you may provide would be highly appreciated. :)

EDIT: People in the comments are saying that it can be a good idea for memory usage / efficiency. However, it is my understand that PHP variables automatically cease to exist once the script is done running. So, would it really help at all with memory usage?

Top answer
1 of 5
45
It seems like whenever I am using it, it is to completely remove a value from an array.
2 of 5
11
One of the sites I built has a background task that imports large CSV files (large as in 50k rows, >10MB) and stores their contents in the database. One of the problems I started running into was hitting the memory limit. This totally baffled me, because I was only ever working with one row at a time; the read loop used fgetcsv until the end of the file. I'd load a row from the file, parse it into a few ORM objects, perform my inserts, and then the loop would flip around to the next row. The most I was ever handling was a few hundred bytes of text, logically there was no reason for me to be running out of memory. So I tried something. At the end of the loop I reset every variable I used in the loop to null. Suddenly, no more memory errors. You see, PHP doesn't perform garbage collection during normal execution because, as you said, all the memory will be cleaned up when the page finishes. So every time the loop ran, new objects were created overtop of the old ones, but the old ones weren't destroyed, just had their reference counters decremented. Setting the variables to null (or using unset()) always triggers garbage collection. It forces PHP to immediately dereference the object, see that the object is no longer being used, and remove it from memory. I'm not sure if it triggers all garbage collection for the running script, or if it just collects the objects in question, but it absolutely saves memory usage when working with large datasets.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ php unset() function
PHP unset() Function - Scaler Topics
September 29, 2023 - In PHP, the unset() function is used to destroy a specified variable or array element, freeing up the memory occupied by it. When unset() is applied to a variable, it removes its existence and any associated value.
Find elsewhere
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ php tutorial โ€บ php unset array
PHP unset Array | Delete an Array Element using unset Fumction
April 5, 2023 - To make the un-setting array functional we need to have an array with some value on that. Letโ€™s say, we have an array named $array1 with some value. Now we need to make this array empty, we can do this by using the PHP unset() function.
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 21246347 โ€บ php-unset-what-does-it-really-do
php unset() what does it really do? - Stack Overflow
The PHP documentation states the following about the unset() language construct: destroys the specified variables. Unset a given variable What does this really mean? Just destroy the variable
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ which-one-is-better-unset-or-var-null-to-free-memory-in-php
Which one is better (unset() or $var = null) to free memory in PHP ? - GeeksforGeeks
July 23, 2025 - Before unset : hello geeks After unset : null: null is used to empty the variable. We can create a null variable by simply assigning it to null. The memory is not freed, but NULL data is re-written or re-assigned on that particular variable. ... <?php // Declare a variable and // set to string $a = "Hello geeks"; echo "Before null : $a"; // Assign null to this variable $a = null; echo "<br>"; // Display result echo "After null : $a"; ?>
Top answer
1 of 16
3648

There are different ways to delete an array element, where some are more useful for some specific tasks than others.

Deleting a Single Array Element

If you want to delete just one single array element you can use unset() and alternatively array_splice().

By key or by value?

If you know the value and don't know the key to delete the element you can use array_search() to get the key. This only works if the element doesn't occur more than once, since array_search() returns the first hit only.

unset() Expression

Note: When you use unset() the array keys wonโ€™t change. If you want to reindex the keys you can use array_values() after unset(), which will convert all keys to numerically enumerated keys starting from 0 (the array remains a list).

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
unset($array[1]);
          // โ†‘ Key of element to delete

Example Output:

[
    [0] => a
    [2] => c
]

array_splice() Function

If you use array_splice() the (integer) keys will automatically be reindex-ed, but the associative (string) keys won't change โ€” as opposed to array_values() after unset(), which will convert all keys to numerical keys.

Note: array_splice() needs the offset, not the key, as the second parameter; offset = array_flip(array_keys(array))[key].

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
array_splice($array, 1, 1);
                  // โ†‘ Offset of element to delete

Example Output:

[
    [0] => a
    [1] => c
]

array_splice(), same as unset(), take the array by reference. You donโ€™t assign the return values back to the array.

Deleting Multiple Array Elements

If you want to delete multiple array elements and donโ€™t want to call unset() or array_splice() multiple times you can use the functions array_diff() or array_diff_key() depending on whether you know the values or the keys of the elements to remove from the array.

array_diff() Function

If you know the values of the array elements which you want to delete, then you can use array_diff(). As before with unset() it wonโ€™t change the keys of the array.

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c", 3 => "c"];
$array = array_diff($array, ["a", "c"]);
                         // โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                         // Array values to delete

Example Output:

[
    [1] => b
]

array_diff_key() Function

If you know the keys of the elements which you want to delete, then you want to use array_diff_key(). You have to make sure you pass the keys as keys in the second parameter and not as values. Keys wonโ€™t reindex.

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_diff_key($array, [0 => "xy", "2" => "xy"]);
                              // โ†‘           โ†‘
                              // Array keys of elements to delete

Example Output:

[
    [1] => b
]

If you want to use unset() or array_splice() to delete multiple elements with the same value you can use array_keys() to get all the keys for a specific value and then delete all elements.

array_filter() Function

If you want to delete all elements with a specific value in the array you can use array_filter().

Example Code:

$array = [0 => "a", 1 => "b", 2 => "c"];
$array = array_filter($array, static function ($element) {
    return $element !== "b";
    //                   โ†‘
    // Array value which you want to delete
});

Example Output:

[
    [0] => a
    [2] => c
]
2 of 16
1429

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */
๐ŸŒ
ScriptVerse
scriptverse.academy โ€บ tutorials โ€บ php-isset-unset-empty.html
PHP isset(), unset(), empty()
Let us take the very first example used in the above section and apply unset() on the variable $hello just after it is assigned to 'HELLO'. As we call isset() on the variable $hello, which was just unset(), it returns false ยท <?php $hello = 'HELLO'; unset($hello); if(isset($hello)) { // the condition fails; echo is not executed echo $hello.