Sanitize $value According to its $type

function sanitize( $value, $type = null )
{
    // Recursive sanitation for arrays and objects
    if ( is_array( $value ) || is_object( $value ) ) {
        $output = array();
        foreach ( (array) $value as $k => $v ) {
            $k = sanitize_key( $k );
            $output[$k] = sanitize( $v, $type );
        }
        return $output;
    }

    // Default to value's actual type
    if ( ! $type ) { $type = gettype( $value ); }

    switch( strtolower( $type ) )
    {
        case 'boolean':
            return boolval( $value );
        case 'integer':
        case 'number':
            return intval( $value );
        case 'double':
        case 'float':
            return floatval( $value );
        case 'null':
            return null;
        case 'resource':
            return $value;
        case 'url':
            return filter_var( rtrim( $value, '/' ), FILTER_SANITIZE_URL );
        case 'email':
            return filter_var( substr( $value, 0, 254 ), FILTER_SANITIZE_EMAIL );
        default:
            // String
            return filter_var( $value, FILTER_SANITIZE_STRING );
    }
}