Best way to clear a PHP array's values

Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

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.