1

I have this trimmer function, it recursively trims all values in array (people put tons of spaces for no reason!):

function trimmer(&$var) {
    if (is_array($var)) {
        foreach($var as &$v) {
            trimmer($v);
        }
    }
    else {
        $var = trim($var);
    }
}
trimer($_POST);

PROBLEM: I would like to add new feature: i want this function also to convert all _ (underscore) in keys to spaces. I know how to convert keys (str_replace('_', ' ', $key)), but i have trouble to make it work in this recursive style...

Input:

$_POST['Neat_key'] = '   dirty value ';

Expected result:

$_POST['Neat key'] = 'dirty value';
Martin
  • 1,312
  • 1
  • 15
  • 18
  • 1
    Changing the key names can potentially be dangerous. Suppose the `$_POST` array has two keys in it, one named `My Data` and another named `My_Data`. You would have to figure out how to handle the potential key collision. In addition, later logic might rely on the keys from `$_POST` matching up with certain HTML controls. If you change the keys on the fly, that logic could break. – Jonah Bishop Aug 16 '12 at 19:09
  • 1
    Web browser converts to $_POST['Word_word']... If i will have two `Word word` and `Word_word`, there will be colision anyway... – Martin Aug 16 '12 at 19:16

2 Answers2

3

Unfortunately, there isn't a way to replace the keys of an array while you loop the array. This is a part of the language, the only way around it is to use a temporary array:

$my_array = array(
    'test_key_1'=>'test value 1     ',
    'test_key_2'=>'        omg I love spaces!!         ',
    'test_key_3'=>array(
        'test_subkey_1'=>'SPPPPAAAAACCCEEESSS!!!111    ',
        'testsubkey2'=>'    The best part about computers is the SPACE BUTTON             '
    )
);
function trimmer(&$var) {
    if (is_array($var)) {
        $final = array();
        foreach($var as $k=>&$v) {
            $k = str_replace('_', ' ', $k);
            trimmer($v);
            $final[$k] = $v;
        }
        $var = $final;
    } elseif (is_string($var)) {
        $var = trim($var);
    }
}
/* output
array (
        'test key 1'=>'test value 1',
        'test key 2'=>'omg I love spaces!!',
        'test key 3'=>array (
                'test subkey 1'=>'SPPPPAAAAACCCEEESSS!!!111',
                'testsubkey2'=>'The best part about computers is the SPACE BUTTON'
        )
)
*/

Try it: http://codepad.org/A0N5AU2g

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
0

This is an oldie but I just saw it in related:

function trimmer(&$var) {
    if (is_array($var)) {
        foreach($var as &$v) {
            trimmer($v);
        }
        // only additional code
        $var = array_combine(str_replace('_', ' ', array_keys($var)), $var);
    }
    else {
        $var = trim($var);
    }
}

But better nowadays would be array_walk_recursive().

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87