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?

2
  • 3
    is_numeric doesn't mean it's an integer. It just means it's a number. Commented Oct 13, 2013 at 4:14
  • Geez, I wasn't paying attention. Thanks for the answers, anyhow. Commented Oct 13, 2013 at 6:17

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.