Recursive trim() function to handle arrays and objects
Avoid if-else nesting to keep things flat. Return inside the first if is enough to do so.



I added is_iterable() so this function can handle more types than just array

/**
 * 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 &amp;trim_r( &amp;$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 = trim( $o, $character_mask ?? " \t\n\r\0\x0B" );
        return $o;
    }

    if( is_iterable($o) || is_object( $o ) )
    {
        // Loop this array/object and apply trim_r() to its members
        foreach( $o as &amp;$v )
        {
            trim_r( $v );
        }

    }

    // Supply this just in case the invoker wishes to receive result as a reference
    return $o;
}