Shortest way to check if a variable contains positive integer using PHP?

后端 未结 6 1766
野性不改
野性不改 2020-12-08 11:04

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 charact         


        
6条回答
  •  孤街浪徒
    2020-12-08 11:37

    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 )
    

提交回复
热议问题