202

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;
}

I don't want to use unset() because that deletes the variable.

TylerH
  • 20,799
  • 66
  • 75
  • 101
el_pup_le
  • 11,711
  • 26
  • 85
  • 142

13 Answers13

307

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

If 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. Bear in mind that re-instantiating a structure is not the same as emptying it.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
  • 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
  • 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
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
  • 272,448
  • 266
  • 850
  • 1,236
  • 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

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Wolfsblvt
  • 1,061
  • 12
  • 27
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
  • 172,118
  • 50
  • 264
  • 308
9

Isn't unset() good enough?

unset($array);
John Conde
  • 217,595
  • 99
  • 455
  • 496
7

How about $array_name = array(); ?

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
7

Use array_splice to empty an array and retain the reference:

array_splice($myArray, 0);

p1100i
  • 3,710
  • 2
  • 29
  • 45
Allan Jardine
  • 5,303
  • 5
  • 30
  • 34
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,061
  • 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
  • 135
  • 1
  • 3
  • @KulshreshthK What that does is that it reinitialize the array and that is very simple, it is like emptying the array or recreating it or bringing it to a reset state – John Max Sep 04 '20 at 14:32
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
  • 193
  • 8
  • This question is in no way seeking a recursive approach. It looks like you are answering your own invented extension of this question's requirements. Researchers who will benefit from your script are unlikely to find your answer on this page. It might be best to ask a new, narrow/specific question and self-answer it. – mickmackusa Oct 13 '22 at 20:40
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,828
  • 4
  • 30
  • 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

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
0

[] is nearly 30% faster then as array() similar as pushing new element to array $array[] = $newElement then array_push($array, $newElement) (keep in mind array_push is slower only for single or 2 new elements)

Reason is we skip overhead function to call those

PHP array vs [ ] in method and variable declaration

  • 1
    `array()` is not a function, [it is a construct](https://www.php.net/manual/en/reserved.keywords.php). Please include your benchmark to support your claims of performance. – mickmackusa Oct 13 '22 at 20:38
  • Added source in post, i have readed few post more from diffrent forums but cannot find them :( – Damian Chudobiński Oct 15 '22 at 15:45