Shortest way to check if a variable contains positive integer using PHP?
Try the native Filter function*
filter_var($value, FILTER_VALIDATE_INT, array(
'options' => array('min_range' => 1)
));
* if you just want to make sure the input string consists of an arbitrary length digit sequence, use a regex with [0-9] or [\d+]
Examples with filter_var
:
var_dump( filter_var(1, FILTER_VALIDATE_INT) ); // int(1)
var_dump( filter_var('1', FILTER_VALIDATE_INT) ); // int(1)
var_dump( filter_var('+10', FILTER_VALIDATE_INT) ); // int(10)
var_dump( filter_var(.1, FILTER_VALIDATE_INT) ); // bool(false)
var_dump( filter_var('.1', FILTER_VALIDATE_INT) ); // bool(false)
var_dump( filter_var(-1, FILTER_VALIDATE_INT,
array('options' => array('min_range' => 1))) ); // bool(false)
var_dump( filter_var('-1', FILTER_VALIDATE_INT,
array('options' => array('min_range' => 1))) ); // bool(false)
var_dump( filter_var('2147483648', FILTER_VALIDATE_INT) ); // bool(false)
var_dump( filter_var('0xFF', FILTER_VALIDATE_INT) ); // bool(false)
var_dump( filter_var(0xFF, FILTER_VALIDATE_INT) ); // int(255)
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 )