Check if a variable is a natural number

后端 未结 9 1848
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: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).

提交回复
热议问题