2

Since it appears intval only returns 0 if it's not an integer (and I want 0 sometimes in the input), and also since is_int doesn't evaluate string input to tell me if it's an integer (and I'm simply not familiar with what casting a variable as (int) does if it's not an integer).

What's the correct way to go about this?

Hamster
  • 2,962
  • 7
  • 27
  • 38
  • 1
    possible duplicate of [Checking if a string holds an integer](http://stackoverflow.com/questions/3377537/checking-if-a-string-holds-an-integer) – outis Mar 11 '11 at 20:25
  • I suppose it is. I'll just use `if((string)(int)$var == $var)` then. Thanks! – Hamster Mar 11 '11 at 20:41

5 Answers5

1

You might want to take a look at the ctype_digit() function (quoting) :

bool ctype_digit ( string $text )
Returns TRUE if every character in the string $text is a decimal digit, FALSE otherwise.

Using this to test what the input is made of, you should then be able to decide what to do with it, depending on the fact it contains an integer or not.


I suppose something like this should do the trick :

if (ctype_digit($_POST['your_field'])) {
    // it's an integer => use it
} else {
    // Not an integer
}
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
0

Maybe try is_numeric. According to the examples in the documentation, this is exactly what you want.

krtek
  • 26,334
  • 5
  • 56
  • 84
0

Could you use is_int in conjunction with is_string?

For example:

if(is_int(x) == 0 && is_string(x))
user387049
  • 6,647
  • 8
  • 53
  • 55
  • No. A variable cannot be of type string and of type int at the same time. The expression you quote is true if `x` is a string and false otherwise—not at all what the OP asked for. –  Jun 20 '11 at 13:01
0
$input =  preg_match("/^[0-9]{1,}$/",$input) ? (int)$input:$input;
matt
  • 320
  • 4
  • 15
  • \d matches decimal digits. http://www.php.net/manual/en/regexp.reference.escape.php \d is the same thing as [0-9] –  Jun 20 '11 at 13:06
0

Same answer as matt but easier to read:

preg_match('/^\d+$/', $x)

But ctype is probably faster if your system has it.