0

OK, I've read some guides, and I'm still a bit confused as to the purpose of this.

I've come across a bit of code in a project that I've picked up from a previous developer, which has items like this all across it:

if (is_numeric($var) && ((int)$var == $var){

What is the purpose of typecasting $var to int in the second check? The whole thing is going to evaluate false if $var is not numeric, or at least a string that can evaluate to numeric. And even if $var is a string and not a number, the second check is going to evaluate to true, again, if the string can evaluate to a number.

Wouldn't it make more sense to just use is_numeric() and leave it at that?

LoganEtherton
  • 495
  • 4
  • 12

3 Answers3

2

This is an attempt to solve a common problem, because of the limitations of certain seemingly obvious strategies:

  • is_numeric($var) returns true for numbers in lots of formats, such as '1.5e10'
  • (int)$var == $var checks that converting the number to an int results in a value that compares back to the original, but for non-numeric strings PHP tries to be clever, so '1a' == 1

If both checks succeed, it's an integer, congratulations.

However, if what you want is a positive integer, ctype_digit((string)$var), which simply checks if the string contains nothing but digits, is a much more compact alternative.

See also: php check to see if variable is integer

Community
  • 1
  • 1
IMSoP
  • 89,526
  • 13
  • 117
  • 169
0

as said in the comment, is_numeric just checks if the variable is a number. The second check (int)$var == $var checks to see if the integer value of the number is equal to the number. In other words, if the number is an integer.

If the number was a real number, is_numeric returns true . But in the second check the real number is casted to an integer. so 3.14 becomes 3, and 3==3.14 fails.

The second check returns true only if the number is an integer.

Shikhar Subedi
  • 606
  • 1
  • 9
  • 26
0

As cole already pointed out, the is_numeric function can tell you whether the particular $var is a numeric value, which may or may not be a integer.

The (int)$var == $var is checking whether it is a integer or not. You could also use is_int for this.

Aayush Agrawal
  • 1,354
  • 1
  • 12
  • 24