Don't Panic
Don't Panic

Reputation: 41810

How do I clear the values in a PHP array while maintaining its keys?

I would like to take an array and clear all of its values while maintaining its keys. By "clear" I mean replace with an empty type value, such as '' or null. PHP obviously has quite a few array functions, but I didn't find anything there that does exactly this. I am currently doing it this way:

foreach ($array as &$value) $value = ''

My question is, is there some built-in php function I overlooked, or any other way I can accomplish this without iterating over the array at this level?

Upvotes: 1

Views: 233

Answers (3)

Darien
Darien

Reputation: 3592

Without knowing exactly what your memory/performance/object-management needs are, it's hard to say what's best. Here are some "I just want something short" alternatives:

$array = array_fill_keys(array_keys($a),""); // Simple, right?

$array = array_map(function(){return "";},$a); // More flexible but easier to typo

If you have an array that's being passed around by reference and really want to wipe it, direct iteration is probably your best bet.

foreach($a as $k => $v){
    $a[$k] = "";
}

Iteration with references:

/* This variation is a little more dangerous, because $v will linger around
 * and can cause bizarre bugs if you reuse the same variable name later on,
 * so make sure you unset() it when you're done.
 */ 
foreach($a as $k => &$v){
    $v = "";
}
unset($v);

If you have a performance need, I suggest you benchmark these yourself with appropriately-sized arrays and PHP versions.

Upvotes: 2

ziollek
ziollek

Reputation: 1993

Easiest way is array_map

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

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

You can use array_keys to get the keys. You can then use array_flip if you like, although this will assign the values 0 through length-1 to the keys.

There is no single built-in function for this. You might try:

array_combine(array_keys($array),array_fill(0,count($array)-1,""));

But really the code you have right now does the job just fine.

Upvotes: 1

Related Questions