1

I would like the code below to return 'Int' the first time and 'Not int' the second time. Unfortunately it returns 'Not int' twice instead.

How can I fix this?

<?php
$test1='1';
if(is_int($test1)){
        echo "Int";
}else{
        echo "Not int";
}

echo "\n";

$test2='1a';
if(is_int($test2)){
        echo "Int";
}else{
        echo "Not int";
}
?>
NullUserException
  • 83,810
  • 28
  • 209
  • 234
GarouDan
  • 3,743
  • 9
  • 49
  • 75

4 Answers4

6

By wrapping the number in quotation marks '1', you are declaring a string. Instead you got to use $test1 = 1;.

By using the PHP ctype_digit() function, you can check if a string only contains digits.
You could also use the is_numeric() function, which also returns true if the string contains a exponential part like +0123.45e6 or a hex value 0xFF.

Zulakis
  • 7,859
  • 10
  • 42
  • 67
2

is_int - Find whether the type of a variable is integer Because you put the number in quotes, it is a string. Therefore is_int = false

is_numeric — Finds whether a variable is a number or a numeric string Because the string is actually a number, is_numeric will return true

So, change is_int to is_numeric and it works:

<?php
$test1 = '1';
if (is_numeric($test1))
{
    echo 'Int';
}
else
{
    echo 'Not int';
}

echo "\n";

$test2 = '1a';
if (is_numeric($test2))
{
    echo 'Int';
}
else
{
    echo 'Not int';
}
?>
Jason
  • 1,192
  • 7
  • 8
  • It might be a good idea to provide explanation of difference between `is_int` and `is_numeric`. – Zbigniew Oct 04 '12 at 16:51
  • is_numeric will be proven true if 1e4 or 909.89 are given. – Wayne Whitty Oct 04 '12 at 16:52
  • It is also a good idea to omit the closing tag (`?>`) at the end of code, as [mentioned by the documentation](http://www.php.net/manual/en/language.basic-syntax.phptags.php) and [outlined at StackOverflow](http://stackoverflow.com/a/4499749/548696). – Tadeck Oct 04 '12 at 17:00
1

Use ctype_digit() instead.

ctype_digit('1'); // True
ctype_digit('1a'); // False
Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
0

change

 $test1='1'; 

to

 $test1=1;
Afshin
  • 4,197
  • 3
  • 25
  • 34