40

Do I really have to do this to reset an array?

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

EDIT:

This one makes more sense, as the previous one is equivalent to $array=array();

foreach ($array as $i => $value) {
    $array[$i]=NULL;
}
3
  • 2
    array_map(function () { return ''; }, $array) Commented Dec 25, 2014 at 20:23
  • See also: equivalent question and answers for python stackoverflow.com/questions/22991888 Commented Jan 6, 2017 at 3:32
  • @jfoucher If you're still around, could you please reject my answer and accept a more suitable one? Commented Jul 26, 2018 at 16:36

13 Answers 13

54
$keys = array_keys($array);
$values = array_fill(0, count($keys), null);
$new_array = array_combine($keys, $values);

Get the Keys

Get an array of nulls with the same number of elements

Combine them, using keys and the keys, and the nulls as the values

As comments suggest, this is easy as of PHP 5.2 with array_fill_keys

$new_array = array_fill_keys(array_keys($array), null);
Sign up to request clarification or add additional context in comments.

3 Comments

+1, these functions come in handy quite often. As of PHP 5.2 there is even array_fill_keys().
+1, both of the above solutions are faster, array_combine being the best among the two.
@DamithRuwan Who uses PHP <= 5.2 nowadays :D
33

Fill array with old keys and null values

$array = array_fill_keys(array_keys($array), null)

1 Comment

It's not clear from OP's question whether this is actually what he meant or wanted - it's what I wanted, so +1 for providing the simplest/shortest possible solution.
13

There is no build-in function to reset an array to just it's keys.

An alternative would be via a callback and array_map():

$array = array( 'a' => 'foo', 'b' => 'bar', 'c' => 'baz' );

With regular callback function

function nullify() {}
$array = array_map('nullify', $array);

Or with a lambda with PHP < 5.3

$array = array_map(create_function('', ''), $array);

Or with lambda as of PHP 5.3

$array = array_map(function() {}, $array);

In all cases var_dump($array); outputs:

array(3) {
  ["a"]=> NULL
  ["b"]=> NULL
  ["c"]=> NULL
}

2 Comments

@stereofrog Right. I've changed the functions. Not that it is wrong with body and argument, but why add clutter... Thanks.
array_fill_keys() is still simpler/KISS solution. Though I like lambda version too.
10

Define this function and call it whenever you need it:

function erase_val(&$myarr) {
    $myarr = array_map(create_function('$n', 'return null;'), $myarr);
}

// It's call by reference so you don't need to assign your array to a variable.
// Just call the function upon it
erase_val($array);

That's all!

4 Comments

I'm sorry, but this is by far the worst answer posted - create_function() is basically eval() and definitely should not be used to solve a problem as trivial as this one. Besides, a function for that is also completely overkill. IMO, this should not be the accepted answer.
@mindplay.dk This answer is just outdated. It was posted at a time were this was the most reliable way to achieve such things. Most webhosts were still on PHP v5.0 at that time. Let's call it a piece of history.
@feeela Piece of history ... for sure, but still outdated.
@aefxx Correct, but “outdated” and “by far the worst answer posted” are two different ratings…
8

Get the array keys, then use them to create a new array with NULL values:

array_fill_keys(array_keys($array), NULL);

About array_fill_keys():

The array_fill_keys() function fills an array with values, specifying keys.

About array_keys():

The array_keys() function returns all the keys of an array.

Comments

2
foreach($a as &$v)
   $v = null;

The reasoning behind setting an array item to null is that an array needs to have a value for each key, otherwise a key makes no sense. That is why it is called a key - it is used to access a value. A null value seems like a reasonable choice here.

Wrap it in a [reusable] procedure:

function array_purge_values(&$a) {
    foreach($a as &$v)
       $v = null;
}

Keep in mind though that PHP versions 5.3 and those released later, pass values to functions by reference by default, i.e. the ampersand preceding argument variable in the function declaration is redundant. Not only that, but you will get a warning that the notion is deprecated.

7 Comments

Easy yes, but it's not reusable. Code like this stinks. Sorry.
@aefxx Then just wrap it into a function and pollute the global scope with the smell of just another userland function
aefxx, you are very welcome to explain why this stinks. This is not a review board, people usually do explain their arguments here. I have edited my post to include exactly what you perhaps felt was missing.
@Gordon He could easily put this in a utility class and call it statically from there - no global scope pollution whatsoever. @amn Well, your code does the trick, for sure. But most likely the programmer won't comment on why he is doing the nullification EVERY time he needs to. So, implementing a reusable function and commenting what it is for (NOT what it does, that's obvious) is best practice. Besides that, it's more error prone as the programmer could have an error EVERY single time he writes that piece of code (unlikely here, but you grasp the concept).
@aefxx If you want to share insight beyond the actual problem, then you are encouraged to do so, but don't tell people their answers stink just because they choose not to. Especially, when the answers are perfectly valid. Also, I find it rather offensive and arrogant to insinuate the OP is obviously unable to wrap a foreach loop into a function or that he is not capable of expressing a wish for an everyday concept like reusability.
|
1

If you need to nullify the values of a associative array you can walk the whole array and make a callback to set values to null thus still having keys

array_walk($ar,function(&$item){$item = null;});

In case if you need to nullify the whole array just reassign it to empty one

$ar = array();

Comments

0

unset would delete the key, You need to set the value to null or 0 as per your requirement.

Example

Comments

0

I don't get the question quite well, but your example

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

is equivilent to

$array = array();

1 Comment

Yes, that's true, The keys get deleted also... I wanted a built-in function to do this : foreach ($array as $i => $value) { $array[$i]=NULL; }
0

Why not making an array with required keys and asinging it to variable when you want reset it?

function resetMyArr(&$arr)
{
 $arr = array('key1'=>null,'key2'=>null); 
}

Comments

0

This is a fairly old topic, but since I referenced to it before coming up with my own solution for a more specific result, so therefore I will share with you that solution.

The desired result was to nullify all values, while keeping keys, and for it to recursively search the array for sub-arrays as well.

RECURSIVELY SET MULTI-LEVEL ARRAY VALUES TO NULL:

function nullifyArray(&$arrayData) {

  if (is_array($arrayData)) {
    foreach ($arrayData as $aKey => &$aValue) {
      if (is_array($aValue)) {
        nullifyArray($aValue);
      } else {
        $aValue = null;
      }
    }
    return true;     // $arrayData IS an array, and has been processed.
  } else {
    return false;    // $arrayData is NOT an array, no action(s) were performed.
  }

}

And here is it in use, along with BEFORE and AFTER output of the array contents.

PHP code to create a multilevel-array, and call the nullifyArray() function:

// Create a multi-level array.
$testArray = array(
    'rootKey1'              =>  'rootValue1',
    'rootKey2'              =>  'rootValue2',
    'rootArray1'            =>  array(
        'subKey1'           =>  'subValue1',
        'subArray1'         =>  array(
            'subSubKey1'    =>  'subSubValue1',
            'subSubKey2'    =>  'subSubValue2'
        )
    )
);

// Nullify the values.
nullifyArray($testArray); 

BEFORE CALL TO nullifyArray():

Array
(
    [rootKey1] => rootValue1
    [rootKey2] => rootValue2
    [rootArray1] => Array
        (
            [subKey1] => subValue1
            [subArray1] => Array
                (
                    [subSubKey1] => subSubValue1
                    [subSubKey2] => subSubValue2
                )

        )

)

AFTER CALL TO nullifyArray():

Array
(
    [rootKey1] => 
    [rootKey2] => 
    [rootArray1] => Array
        (
            [subKey1] => 
            [subArray1] => Array
                (
                    [subSubKey1] => 
                    [subSubKey2] => 
                )

        )

)

I hope it helps someone/anyone, and Thank You to all who previously answered the question.

Comments

0

And speed test This test shows speed when clearing a large array

$a1 = array();
for($i=0;$i<=1000;$i++)
{
    $a1['a'.$i] = $i;
}
$b = $a1;
$start_time = microtime(TRUE);
    foreach ($a1 as $field => $val) {
      $a1[$field]=NULL;
    } 
$end_time = microtime(TRUE);
$duration = $end_time - $start_time;
var_dump( $duration*1000 );

var_dump('all emelent of array is '.reset($a1));


$start_time = microtime(TRUE);
$allkeys = array_keys($b);
$newarray = array_fill_keys($allkeys, null);

$end_time = microtime(TRUE);
$duration = $end_time - $start_time;
var_dump( $duration*1000 );

var_dump('all emelent of array is '.reset($newarray));

Comments

-1

Just do this:

$arrayWithKeysOnly = array_keys($array);

http://php.net/manual/en/function.array-keys.php

EDIT: Addressing comment:

Ok, then do this:

$arrayWithKeysProper = array_flip(array_keys($array));

http://www.php.net/manual/en/function.array-flip.php

EDIT: Actually thinking about it, that probably won't work either.

4 Comments

This would return an array with keys being the values and is not what the OP wants. He wants to keep the keys and just purge the values
array_flip won't do either, because the array values would be ascending then, e.g. 'a' => 0, 'b' => 1 and so on
yeah, I'd say you gotta walk it.
doing this and getting a bug was exactly what brought me to this page :) -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.