PHP checking for a number

How to check if a variable is a positive integer in php. It is an integer (fractional is not allowed), i.e. is_numeric function is not suitable. ( is_int doesn’t work either)


Answer 1, authority 100%

if (($val = intval($val)) && ($val > 0))
  ...

Answer 2, authority 33%

if (preg_match('/^\+?\d+$/', $value)) {
    echo "   :-)";
}

Answer 3, authority 33%

You can do this:

if ($value && ctype_digit((string)$value)) {
    echo "$value is positive integer\n";
}

Or like this:

$value = filter_var($value, FILTER_VALIDATE_INT, array("options" => array("min_range" => 1)));
if ($value !== faslse) {
    echo "$value is positive integer\n";
}

Answer 4, authority 33%

if(intval($a) === $a && $a > 0){...}

Answer 5, authority 33%

if(is_integer($int) && $int > 0){
   echo ' .    ';
}
else{
   echo ',  ';
}

Answer 6, authority 33%

if ( ( is_int( $a ) || ctype_digit( $a ) ) && $a > 0 )
if ( ( is_int( $a ) || (string) intval( $a ) === $a ) && $a > 0 )
if ( ( preg_match( '/^[1-9]\d*$/', $a ) ) || ( is_int( $a ) && $a > 0 ) )

P.S: There are an infinite number of ways to solve your vaguely worded question


Answer 7

$a = 100;
//$a = '1a';
//$a = 0;
//$a = '1,1';
//$a = 1.1;
//$a  = 'a';
if(!intval($a) or $a < 1 or !preg_match('/^\+?\d+$/', $a))
{
    echo 'BaD';
}
else
{
    echo 'GooD';
}

Answer 8

if ($val *= 1 && $val > 0) {
    echo 'ok';
}

🙂


Answer 9

a gettype() ?


Answer 10

function is_whole_int($val) {
    return is_numeric($val) && floor($val) == $val && $val > 0;
}
var_dump(is_whole_int(5.8)); // false
var_dump(is_whole_int(0)); // false
var_dump(is_whole_int(-1)); // false
var_dump(is_whole_int(5)); // true

Redesigned from here https://stackoverflow.com/questions/6772603/check-if-number -is-decimal
It is quite logical to round up to an integer and compare the value. If you need a number, including 0, then
return is_numeric( $val ) && floor( $val ) == $val && $val >= 0;


Answer 11

There are already a lot of options, but I would probably do it like this

if (((int) $val === intval($val)) && intval($val) > 0 && 
preg_match('/^\d+$/', $val))
{
    echo 'is int';
}
else
{
    echo 'not int or < 0';
}

Answer 12

Alternatively, check is_numeric first, and then check that there are no ‘+’ and ‘.’ signs in the string. and ‘,’


Answer 13

if(is_numeric($val) && intval($val)>0 && intval($val) == ceil(intval($val))) {
}

Answer 14

I like this solution, I always use it:

$v = "dfgf";
if ((int)$v) > 0) {
  echo " ";
}