Trim array (recursive)
Cleans a entire array recursivly.
/** * Trims a entire array recursivly. * * @author Jonas John * @version 0.2 * @link https://www.jonasjohn.de/snippets/php/trim-array.htm * @param array $Input Input array */ function TrimArray($Input){ if (!is_array($Input)) return trim($Input); return array_map('TrimArray', $Input); } /* Old version (v0.1): function TrimArray($arr){ if (!is_array($arr)){ return $arr; } while (list($key, $value) = each($arr)){ if (is_array($value)){ $arr[$key] = TrimArray($value); } else { $arr[$key] = trim($value); } } return $arr; } */
Snippet Details
-
AuthorJonas
-
LicensePublic Domain
-
LanguagePHP
-
Created03/28/2006
-
Updated10/01/2007
-
Tagsarray functions, string functions
$DirtyArray = array( 'Key1' => ' Value 1 ', 'Key2' => ' Value 2 ', 'Key3' => array( ' Child Array Item 1 ', ' Child Array Item 2' ) ); $CleanArray = TrimArray($DirtyArray); var_dump($CleanArray); /* Result will be: array(3) { ["Key1"]=> string(7) "Value 1" ["Key2"]=> string(7) "Value 2" ["Key3"]=> array(2) { [0]=> string(18) "Child Array Item 1" [1]=> string(18) "Child Array Item 2" } } */
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
Stewart May 05, 2011 at 12:28
Very nice, thanks.
James August 12, 2010 at 01:44
Actually this is a more general solution:
function array_map_r($func, $arr)
{
return is_array($arr) ? array_map('array_map_r', array_fill(0, count($arr), $func), $arr) : call_user_func($func, $arr);
}
Then just call:
array_map_r("trim", $arr);
function array_map_r($func, $arr)
{
return is_array($arr) ? array_map('array_map_r', array_fill(0, count($arr), $func), $arr) : call_user_func($func, $arr);
}
Then just call:
array_map_r("trim", $arr);
James August 12, 2010 at 00:35
Neat. This is what I'm going to use:
function trim_r($arr)
{
return is_array($arr) ? array_map('trim_r', $arr) : trim($arr);
}
function trim_r($arr)
{
return is_array($arr) ? array_map('trim_r', $arr) : trim($arr);
}
jizzle July 15, 2010 at 16:30
Thank you, very helpful. However, instead of creating a new function, you could just use the trim function as the callback for array_map, for example:
array_map('trim', $arr);
array_map('trim', $arr);