Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

validation - Best way to check for positive integer (PHP)?

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_value;
if (!is_numeric($i) || $i < 1 || $i != round($i)) {
  return TRUE;
}

I was wondering if there's any advantage to using the three checks above, instead of just doing something like so:

$i = $user_input_value;
if (!is_int($i) && $i < 1) {
  return TRUE;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...