PHP need to trim all the $_POST variables

Here's a one-liner that will also work either on single values or recursively on arrays:

$_POST = filter_var($_POST, \FILTER_CALLBACK, ['options' => 'trim']);

Simply

  $_POST = array_map("trim", $_POST);

But if $_POST members (even if 1 of them) is again an array itself, then use recursive version:

    function array_map_deep( $value, $callback ) 
    {
        if ( is_array( $value ) ) {
            foreach ( $value as $index => $item ) {
                    $value[ $index ] = array_map_deep( $item, $callback );
            }
        } elseif ( is_object( $value ) ) {
            $object_vars = get_object_vars( $value );
            foreach ( $object_vars as $property_name => $property_value ) {
                    $value->$property_name = array_map_deep( $property_value, $callback );
            }
        } else {
            $value = call_user_func( $callback, $value );
        }
        return $value;
    }

Tags:

Php