200

Which is more efficient for clearing all values in an array? The first one would require me to use that function each time in the loop of the second example.

foreach ($array as $i => $value) {
    unset($array[$i]);
}

Or this

foreach($blah_blah as $blah) {
    $foo = array();
    //do something
    $foo = null;
}
el_pup_le
  • 10,711
  • 22
  • 77
  • 130

14 Answers14

298

Like Zack said in the comments below you are able to simply re-instantiate it using

$foo = array(); // $foo is still here

If you want something more powerful use unset since it also will clear $foo from the symbol table, if you need the array later on just instantiate it again.

unset($foo); // $foo is gone
$foo = array(); // $foo is here again
Eric Herlitz
  • 23,976
  • 26
  • 110
  • 154
  • 67
    Why not just re-instantiate it as `$foo = array();`? – Zack Zatkin-Gold Nov 22 '13 at 00:13
  • 1
    if it is a global array – Nisham Mahsin Apr 03 '14 at 14:26
  • 2
    @NishamMahsin Either use `global $foo; unset($foo);` or `unset($GLOBALS['foo']);` – Eric Herlitz Apr 03 '14 at 15:29
  • 1
    Downvoted: Why do you have to use unset()? is there any problem in using just "$foo = array();" without the unset? WHY? – javier_domenech Nov 10 '14 at 11:33
  • 7
    @vivoconunxino I wrote it that way because of the authors question "Best way to clear a PHP array's values". It sais 'clear', not 'new instance'. Using `unset` will clear `$foo` from the symbol table. I we are talking about very large tables I'd probably recommend `$foo = null; unset($foo);` since that also would clear the memory a bit better. That behavior (GC) is however not very constant and may change over PHP versions. – Eric Herlitz Nov 10 '14 at 11:52
  • So from the memory usage point of view it's better than the other options... mmm ok! Thank you for your response – javier_domenech Nov 10 '14 at 12:50
  • 1
    @vivoconunxino It is, but it also takes a bit longer. Analyze and implement, as always :) – Eric Herlitz Nov 10 '14 at 19:41
  • 5
    unset() is sometimes very bad and can cause trouble, if you use it wrong. It doesn't answer the OPs answer correctly. Don't know why he accepted this as best answer, his comment on his own question says the problem with unset is it deletes the variable. To see wich problems this solutions causes, take a look at my answer [here](http://stackoverflow.com/questions/10261925/best-way-to-clear-a-php-arrays-values/22664705#22664705). – Wolfsblvt Dec 10 '14 at 14:28
  • 2
    To all supporting `$foo = array();`: actually there might be a conceptual problem in it: re-instantiating a structure is not the same as emptying it. When dealing with memory you know it's not the same thing as allocation is slow. So, despite the ease of use, re-instantiation might not be the answer to this question, especially if one needs to do it a lot of times and quickly. It might work, but that would heavily rely on PHP memory management, IMO. – TechNyquist Feb 18 '20 at 17:42
  • 1
    @TechNyquist hence my advice on using unset :) – Eric Herlitz Feb 18 '20 at 18:00
95

If you just want to reset a variable to an empty array, you can simply reinitialize it:

$foo = array();

Note that this will maintain any references to it:

$foo = array(1,2,3);
$bar = &$foo;
// ...
$foo = array(); // clear array
var_dump($bar); // array(0) { } -- bar was cleared too!

If you want to break any references to it, unset it first:

$foo = array(1,2,3);
$bar = &$foo;
// ...
unset($foo); // break references
$foo = array(); // re-initialize to empty array
var_dump($bar); // array(3) { 1, 2, 3 } -- $bar is unchanged
mpen
  • 256,080
  • 255
  • 805
  • 1,172
  • 3
    I think this is the best answer. Should be accepted. It shows the simplest way and also describes why and when `unset` should be used. +1 –  Mar 06 '17 at 16:40
  • This is my code: https://justpaste.it/1gt46. How can i declare more than one id's in variable. Single value declaration is : $productId = 19; How can i declare more than one value in $productId=? – Gem Feb 08 '18 at 08:53
  • @Rathinam Not sure what that has to do with clearing an array. Please post a new question on Stackoverflow, and paste your code directly into the question. – mpen Feb 08 '18 at 17:07
33

Sadly I can't answer the other questions, don't have enough reputation, but I need to point something out that was VERY important for me, and I think it will help other people too.

Unsetting the variable is a nice way, unless you need the reference of the original array!

To make clear what I mean: If you have a function wich uses the reference of the array, for example a sorting function like

function special_sort_my_array(&$array)
{
    $temporary_list = create_assoziative_special_list_out_of_array($array);

    sort_my_list($temporary_list);

    unset($array);
    foreach($temporary_list as $k => $v)
    {
        $array[$k] = $v;
    }
}

it is not working! Be careful here, unset deletes the reference, so the variable $array is created again and filled correctly, but the values are not accessable from outside the function.

So if you have references, you need to use $array = array() instead of unset, even if it is less clean and understandable.

Wolfsblvt
  • 1,004
  • 12
  • 27
  • 3
    this should be the answer - the OP says clear arrays values, not de-reference the entire array variable. – Ross Jun 28 '15 at 12:37
13

I'd say the first, if the array is associative. If not, use a for loop:

for ($i = 0; $i < count($array); $i++) { unset($array[$i]); }

Although if possible, using

$array = array();

To reset the array to an empty array is preferable.

Madara's Ghost
  • 165,920
  • 50
  • 255
  • 304
9

Isn't unset() good enough?

unset($array);
John Conde
  • 212,985
  • 98
  • 444
  • 485
7

How about $array_name = array(); ?

Bibhas Debnath
  • 14,035
  • 16
  • 67
  • 95
6

Use array_splice to empty an array and retain the reference:

array_splice($myArray, 0);

p1100i
  • 3,610
  • 2
  • 27
  • 44
Allan Jardine
  • 5,071
  • 5
  • 27
  • 31
3

i have used unset() to clear the array but i have come to realize that unset() will render the array null hence the need to re-declare the array like for example

<?php 
    $arr = array();
    array_push($arr , "foo");
    unset($arr); // this will set the array to null hence you need the line below or redeclaring it.
    $arr  = array();

    // do what ever you want here
?>
Wolfsblvt
  • 1,004
  • 12
  • 27
Blessing
  • 31
  • 1
3

Maybe simple, economic way (less signs to use)...

$array = [];

We can read in php manual :

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

PHP php
  • 91
  • 1
  • 3
1

I see this questions is realla old, but for that problem I wrote a recursive function to unset all values in an array. Recursive because its possible that values from the given array are also an array. So that works for me:

function empty_array(& $complete_array) {
    foreach($complete_array as $ckey => $cvalue)
    {
        if (!is_array($cvalue)) {
            $complete_array[$ckey] = "";
        } else {
            empty_array( $complete_array[$ckey]);
        }

    }
    return $complete_array;

}

So with that i get the array with all keys and sub-arrays, but empty values.

Bueck0815
  • 173
  • 8
1

For PHP >= 5.4 use

$var = []; 

Not sure if it's faster than

$var = array();

but at least looks cleaner.

luenib
  • 190
  • 2
  • 14
0

The unset function is useful when the garbage collector is doing its rounds while not having a lunch break;

however unset function simply destroys the variable reference to the data, the data still exists in memory and PHP sees the memory as in use despite no longer having a pointer to it.

Solution: Assign null to your variables to clear the data, at least until the garbage collector gets a hold of it.

$var = null;

and then unset it in similar way!

unset($var);
Waqar Alamgir
  • 9,360
  • 4
  • 28
  • 36
  • 4
    That doesn't sound right. I don't think setting it to `null` will force an immediate garbage collection. Do you have a reference for that? – mpen Jul 02 '15 at 15:34
  • @mpen Do you agree that assigning `NULL` will replace the value stored at the location of the `$var` variable in this example? – Anthony Rutledge Dec 14 '15 at 13:08
  • 1
    @AnthonyRutledge No, I don't. For all I know, PHP will simply update `$var` to point to some global `NULL` object and leave `$var`'s data alone until it's garbage collected. Why would the interpreter be forced to overwrite that data immediately? – mpen Dec 14 '15 at 17:10
  • @mpen That is a good question, but in that world at least everything is ready to be collected. – Anthony Rutledge Dec 14 '15 at 22:46
  • Indeed. Point is that I doubt setting it to null before unsetting it will help any – mpen Dec 15 '15 at 01:21
0

This is powerful and tested unset($gradearray);//re-set the array

Charles
  • 11
0

The question is not really answered by the posts. Keeping the keys and clearing the values is the focus of the question.

foreach($resultMasterCleaned['header'] as $ekey => $eval) {
    $resultMasterCleaned[$key][$eval] = "";                 
}

As in the case of a two dimensional array holding CSV values and to blank out a particular row. Looping through seems the only way.

Paul
  • 1
  • 1