Best way to check for positive integer (PHP)?

前端 未结 20 2197
心在旅途
心在旅途 2020-12-02 18:34

I need to check for a form input value to be a positive integer (not just an integer), and I noticed another snippet using the code below:

$i = $user_input_v         


        
相关标签:
20条回答
  • 2020-12-02 19:16

    Not sure why there's no suggestion to use filter_var on this. I know it's an old thread, but maybe it will help someone out (after all, I ended up here, right?).

    $filter_options = array( 
        'options' => array( 'min_range' => 0) 
    );
    
    
    if( filter_var( $i, FILTER_VALIDATE_INT, $filter_options ) !== FALSE) {
       ...
    }
    

    You could also add a maximum value as well.

    $filter_options = array(
        'options' => array( 'min_range' => 0,
                            'max_range' => 100 )
    );
    

    Learn more about filters.

    0 讨论(0)
  • 2020-12-02 19:16

    If you use "is_int" the variable must be integer, so it can't be a float value. (no round needed).

    0 讨论(0)
提交回复
热议问题