views:

600

answers:

4

I want to check if user input a positive integer number.

1    = true
+10  = true
.1   = false
-1   = false
10.5 = false


Just a positive number. 
No characters.
No special character.
No dot.
No minus sign.

I tried is_int() function but it is returning false even on positive integers. Is there a string to int problem?

Thanks

+8  A: 

Something like this should work. Cast the value to an integer and compare it with its original form (As we use == rather than === PHP ignores the type when checking equality). Then as we know it is an integer we test that it is > 0. (Depending on your definition of positive you may want >= 0)

$num = "20";

if ( (int)$num == $num && (int)$num > 0 )
Yacoby
Call to undefined function int() error
NAVEED
@NAVEED It may be because you are doing `int($num)`. Casting is done by surrounding the type you want to cast to in brackets. In this case `(int)$num`.
Yacoby
Its working. thanks.
NAVEED
+5  A: 
Gordon
and what about abcd, 123d, 10.5 and (space) ??
NAVEED
@NAVEED try yourself and tell me :) I predict all `false`
Gordon
You have to wait.. leaving ;)
NAVEED
A: 

the easiest way is:

if intval($x) > 0 echo "true"

Nopcea Flavius
intval('1e10'); // 1 and intval('420000000000000000000'); // 2147483647
Gordon