Check if a variable is a natural number

后端 未结 9 1827
Happy的楠姐
Happy的楠姐 2020-12-10 16:49

I want to make a bid system on a website. That means users can post their bid (natural number). I want to make sure users don\'t try to post characters, decimal numbers, etc

相关标签:
9条回答
  • 2020-12-10 17:32

    simple function:

    function isnature($x){
    $y = ceil($x)-floor($x);
    return $y == 0 ? true : false;
    }
    
    0 讨论(0)
  • 2020-12-10 17:34

    If you don't require decimal points: ctype_digit or filter_var($var, FILTER_VALIDATE_INT).
    If you do: filter_var($var, FILTER_VALIDATE_FLOAT).

    0 讨论(0)
  • 2020-12-10 17:39

    This kind of depends on your definition of natural numbers - according to different theories, the number zero (0) does or does not count as a natural number.

    To answer your question on how to solve this with preg_match:

    If you want to include zero, using preg_match is pretty easy preg_match('^[0-9]+$', $input).
    Usage:

    if (preg_match('^[0-9]+$', $input))
      // $input represents a non-negative numeric value
    else
      // $input does not represent a non-negative numeric value
    

    If you don't want to include the zero, use preg_match('^[1-9][0-9]*$', $input):

    if (preg_match('^[1-9][0-9]*$', $input))
      // $input represents a positive numeric value
    else
      // $input does not represent a positive numeric value
    

    That said - for your particular problem, using ctype_digit is a faster solution, as others already pointed out (you'd have to do a second check if you don't want to allow the number zero).

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