Categories

# PHP is_numeric() vs is_int() Some lessons you don’t forget, but this one I did because it doesn’t come up very often.

Don’t use is_int() because, as Jeremy says, it’ll lie to you. Use is_numeric() instead.

Copy the following chunk of code into a php file and run it. You’ll be surprised at the outcome:

```\$t = "12345"; if( is_int(\$t ) ) {     echo \$t . " is an int!"; } else {     echo \$t . " is not an int!"; }```

The problem is that is_int() thinks a string of numbers is a string, not an integer. The is_int() man page has an example illustrating that but it’s easy to miss. That function should carry a public health warning!

There’s also the ctype_digit() function too but it has it’s own gotcha:

Note: This function require a string to be useful, so for example passing in an integer will always return FALSE. However, also note that HTML Forms will result in numeric strings and not integers. See also the types section of the manual.

## By Donncha

Donncha Ó Caoimh is a software developer at Automattic and WordPress plugin developer. He posts photos at In Photos and can also be found on Twitter.

## 19 replies on “PHP is_numeric() vs is_int()”

The naming of those two functions is probably too subtle. The key difference between the two is the one checks the type of variable, is_int(), and the other checks the value of the variable, is_numeric().

Also: if the number is bigger than an int. For instance, Flickr photo IDs have passed the integer limit.

Actually this sort of confusion is more widespread than you might think.

Certainly in Oracle 7 (but it might have changed in later versions) if you had a VARCHAR2 column then it was perfectly legitimate to do:

If column=27 then do something.

as long as the column only ever contained numbers. The minute any row in that column contained a character then the If logic given above would break with a type mismatch because the column and the value were no longer the same type. I know, I know.. they weren’t to start with but it was obviously something to do with how Oracle typed its data structures.

Oracle always stores it value according to the declared type, in this example COLUMN is stored as VARCHAR2.

With that declared, Oracle automatically applies datatype conversion, where necessary, and possible. So to process this

COLUMN = 27

So… 27 (INT) is automatically converted to “27” (varchar2), which is then stored in COLUMN.

One must be aware of when type conversions automatically happen in Oracle.

I think the real less here is don’t use is_int if you’re not looking to find out if the variable in question is of type int 🙂

Maybe my Java-based introduction to programming is showing, but that differentiation wasn’t revelation to me.

“The problem is that is_int() thinks a string of numbers is a string, not an integer.”

It’s not a problem, it tells you which data type the variable really holds.

I think Ross has the right of it. Use the right function for the right task.

any legitimate use for is_int() then? usually i just put (int) infront of something to make sure its an int rather than checking

`(int)` is for casting to an int. `is_int()` is for type checking.

```\$foo = (int) 'bar'; // 0 \$foo = (int) 8.2; // 8 \$foo = (int) '8'; // 8```

``` ```

```is_int(8); // true is_int('foobar'); // false```

Completely different.

Second bit of code got screwed up. Here it is again:

```\$foo = is_int(8); // true \$foo = is_int('foobar'); // false```

Dankoozy, it really depends on your coding style and sometimes the specifics of your application. This can be a good way to catch errors in your code. Let’s say I have a load_user function that takes a user ID and loads it from the database. I might want to throw an exception when the input is not an int. However, in most applications which use “1” and 1 interchangeably, this would create a lot of false positives.

One could go through entire projects without ever wanting to use is_int, but sometimes you want to error out when a non-int is provided, as opposed to just casting it to an int.

Try var_dump( (int) “hello” );
You will receive 0
0 is also false where as “hello” would equate to true.
This is where you lose your original definition and could potentially break an algorithm.

A good example of this would be:
``` function getPercentage() { \$temp = func_get_args(); if( is_numeric( \$temp ) ) { \$myValue = (int) \$temp; } if( is_string( \$temp ) && !is_numeric( \$temp ) ) { \$myValue = \$temp; } if( is_int(\$myValue) ){ print (\$myValue * 100) . "%"; //had we done (int) to the string we would have done 0 * 100 }else{ print \$myValue; //For some reason the percentage was already entered. } } ```

It’s also very handy for date functions.
Keeping track of numeric, string, and integer values would be also needed.
if today where Monday, date(“N”) would be “1” not 1.

It’s important to note the description of the function before using it.

(from php.net)
is_int: Find whether the type of a variable is integer
is_numeric: Finds whether a variable is a number or a numeric string

PHP is a loosely typed language. It doesn’t enforce typing, but it does keep track of types to a degree. Since it’s loosely typed, you can usually avoid functions that talk about the *type* of a variable. For example, is_int helps you probe the *type* of a variable, which is very different from the *contents* of the variable (even in a loosely typed language like PHP).

is_numeric is concerned with the *contents* of the variable, not the type. It tells you if the variable is a number (123) or a numeric string (“123”).

9 SaNdDy 3 says:

Thkx

It’s a type check. It’s doing what it is suppose to. If you’re looking to ensure a value, than use a filter_var instead.

\$var = “123456”;
\$var is a string of numbers, not an integer value.
Therefor is_int should return false as it’s not an integer, it’s a string.
However it is a numeric string, so hence is_numeric is true.

For example false is a boolean value, whereas “false” is not. It is a string that would evaluate to true.
You would not want a string mixed with the boolean type, the same applies to integers and strings.
Try this
if ( false ) {
print “You’ll never see this”;
}
if ( true ) {
print “Hello World”;
}
if ( “false” ) {
print “If I were actually false this line shouldn’t be here”;
}

surreal5335 says:

If you used is_numeric() on everything that holds numbers then you wouldbe missing an important factor that could lead to serious problems.

is_numeric looks for strings holding numbers.
is_int() looks for integers

integers can do math and be iterated with, strings cant.

This is not a bug with PHP, this is a lack of a fundamental programming skill.

While I dont like Java, learning java would burn this concept into ones brain bc of its variable type instantiation requirement.

if someone want to inform users instead of converting numbers I found a trick
{"ft_lang_label":"__label__en","ft_lang_prob":0.8755348,"math_prob":0.8989712,"size":6817,"snap":"2022-40-2023-06","text_gpt3_token_len":1652,"char_repetition_ratio":0.11830325,"word_repetition_ratio":0.023198012,"special_character_ratio":0.25920492,"punctuation_ratio":0.11308204,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9567095,"pos_list":[0,1,2],"im_url_duplicate_count":[null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-09-26T03:49:56Z\",\"WARC-Record-ID\":\"<urn:uuid:b8daf2e0-a264-432c-8954-bdcc1e616fc8>\",\"Content-Length\":\"128732\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1890852f-25a2-4d5e-bea3-d5d383a31a91>\",\"WARC-Concurrent-To\":\"<urn:uuid:a630446a-05a2-4a90-9c72-45ad30c4fd71>\",\"WARC-IP-Address\":\"172.105.153.242\",\"WARC-Target-URI\":\"https://odd.blog/2009/03/31/php-is_numeric-vs-is_int/\",\"WARC-Payload-Digest\":\"sha1:IDKSYVLI56BIBHAABDTSFGEWF4BHKOBI\",\"WARC-Block-Digest\":\"sha1:QUF4JNKTKW4FSFEAFIDFIQEA7G4RQHWJ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030334644.42_warc_CC-MAIN-20220926020051-20220926050051-00630.warc.gz\"}"}