Vijay Sinha Vijay Sinha - 4 months ago 15
PHP Question

"is_int" is not working properly?

I am trying to check, Input is an integer, float or string. This program gives an error on negative inputs, I don't understand why this happen. When i check inputs with "ctype_digit()", is_int section escaped.

<?php
$var=fgets(STDIN);
if(is_numeric($var))
{
//print "$var";
if(ctype_digit($var) || is_int($var)){
print "$var";
print "This type of input is Integer";
}
else{
//print "$var";
print "This type of input is Float";
}
}
else{
print "This type of input is String";
}
?>

kip kip
Answer

From PHP MANUAL :

ctype_digit

Note: This function expects a string to be useful, so for example passing in an integer may not return the expected result. However, also note that HTML forms will result in numeric strings and not integers. See also the types section of the manual.

is_int

Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Use a filter like this filter_var($var, FILTER_VALIDATE_INT) for an integer evaluation.

<?php

$var = -10.12;

if(is_numeric($var))
{
    //print "$var";
   if(filter_var($var, FILTER_VALIDATE_INT)){
    var_dump(filter_var($var, FILTER_VALIDATE_INT));
       print "$var";
       print "This type of input is Integer";
   }
   else{
       //print "$var";
       print "This type of input is Float";
   }
}
else{
    print "This type of input is String";
}
?>
Comments