Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a variable is a natural number

Tags:

php

numbers

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. I don't want to use is_numeric function because hexadecimal notation is allowed. I was thinking to use preg_match for this. But in php.net the documentation for this function is little and I have no idea how to use preg_match.

So how should I check if a variable is a natural number with preg_match?

like image 349
Florin Frătică Avatar asked Jul 03 '11 14:07

Florin Frătică


2 Answers

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).

like image 111
deceze Avatar answered Oct 14 '22 11:10

deceze


ctype_digit does what you want:

Checks if all of the characters in the provided string, text, are numerical.

(Before PHP 5.1.0, this function returned TRUE when text was an empty string.)

like image 24
fvu Avatar answered Oct 14 '22 11:10

fvu