I have come up with a recursive function which applies trim()
recursively to all string members of an array/object.
I don't have any specific quandaries about my code so I am receptive to all feedback.
My goal is maximum compatibility for all PHP versions: past, present, and future.
<?php
/**
* trim_r
*
* Recursively trim an array's or object's string values
* Preserves all non-string values
*
* @access public
* @param mixed
* @param mixed
* @return mixed
*/
function &trim_r( &$o, $character_mask = null )
{
// Only apply trim() to strings
if( is_string( $o ) )
{
// Respect the $character_mask; cannot pass null as 2nd parameter for some HHVM versions
$o = ( $character_mask === null ? trim( $o ) : trim( $o, $character_mask ) );
}
elseif( is_array( $o ) || is_object( $o ) )
{
// Loop this array/object and apply trim_r() to its members
foreach( $o as &$v )
{
trim_r( $v );
}
}
// Supply this just in case the invoker wishes to receive result as a reference
return $o;
}