Tuesday 4 September 2018

How can I erase the values ​​in a PHP array while holding 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?

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_values($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.

0 comments:

Post a Comment