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
simple function:
function isnature($x){
$y = ceil($x)-floor($x);
return $y == 0 ? true : false;
}
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).
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).