Assuming that you only want (and only) real integers, and you don't want users to mess up your data and database with hexadecimal or binary or any other form of numbers, you can always use this method:
if(((string) (int) $stringVariable) === $stringVariable) {
The trick is simple. It passes a variable of type string to an integer type, and then returns it to a string. Super fast, super simple.
For testing, I prepared a test:
'1337' is pure integer. '0x539' is not. '02471' is not. '0000343' is not. '0b10100111001' is not. '1337e0' is not. 'not numeric' is not. 'not numeric 23' is not. '9.1' is not. '+655' is not. '-586' is pure integer.
The only place this method crashes is negative numbers, so you need to check that next to it (use ((string) (int) $stringVariable) === $stringVariable && $stringVariable[0] !== "-" ).
Now I thought the preg_match method is the best. but in any project that concerns users, speed is an important factor. so I prepared a test test, doing it 500,000 times higher than the test, and the results were amazing:
My own invented method only took:
6.4700090885162
seconds to complete compared to preg_match , which took:
77.020107984543 seconds to complete this test!
Amirhossein
source share