How to check if a variable is an integer with PHP

PHP has a variety of functions and approaches to determine if a variable is a number and/or an integer. The problem is that many of the straight forward approaches can result in false positives depending on how they react to type juggling. Case in point, is_int() will return false for the string “123”, we could use is_numeric() but that will return true for both “123” and the decimal number 1.23, and both functions will return true if you cast a string as an integer like this: (int)"String!".

In the scenario where you want to determine if a variable is a string (regardless if it’s a string or a number to begin with) you can simply use preg_match() to determine if the string contains just numbers:

preg_match('/^[0-9]+$/', trim($variable
preg_match('/^d+$/',    trim($variable

Note that we trim the variable in the scenario when it’s provided from user input, you can read more about it here](/how-to-strip-whitespace-from-a-string/).

There is another function that you could use but it is only meant to work on strings and returns false if the variable is an actual integer. That function is ctype_digit() and you can trick it by casting (string) when you call it:

ctype_digit(trim((string)$variable

If the $variable in question is known to always be a string (like in the case of user input and often times data being returned from a database) you can simply omit the cast, better safe than sorry though!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.