Is there a difference between is_int() and ctype_digit()?

Viewed 21903

Is one more preferred, or performs better over the other?

7 Answers

is_int() returns true if the argument is an integer type, ctype_digit() takes a string argument and returns true if all the characters in the string are digits.

Example:

┌──────────┬───────────┬────────────────┐
│          │  is_int:  │  ctype_digit:  │
├──────────┼───────────┼────────────────┤
│ 123      │  true     │  false         │
├──────────┼───────────┼────────────────┤
│ 12.3     │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ "123"    │  false    │  true          │
├──────────┼───────────┼────────────────┤
│ "12.3"   │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ "-1"     │  false    │  false         │
├──────────┼───────────┼────────────────┤
│ -1       │  true     │  false         │
└──────────┴───────────┴────────────────┘

The last thing you should be worrying about is how fast one of these is. There is no way that checking a string for being an integer is going to be a bottleneck in your code.

If you don't really care if the argument is a int type or a string with numbers, use is_numeric. It will return true for floats also, tho.

Related