Recursively change keys in an array
I have this function trimmer
, it recursively truncates all values in the 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 a new function: I want this function to also convert everything _
(underscore) to keys to spaces. I know how to convert keys ( str_replace('_', ' ', $key)
), but I have a problem getting it to work in this recursive style ...
Input:
$_POST['Neat_key'] = ' dirty value ';
Expected Result:
$_POST['Neat key'] = 'dirty value';
source to share
Unfortunately, there is no way to replace array keys while looping the array. This is part of the language, the only way 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
source to share
It's old, but I just saw her in a relationship:
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 array_walk_recursive () is now better .
source to share