1

Is there a function in PHP that returns true if a string/int could be safely converted into an int? like so:

var_dump(f('1'));//returns true
var_dump(f(1));//returns true
var_dump(f('1.2'));//returns false
var_dump(f(-2));//returns true
var_dump(f('3x'));//returns false

I do not care about bases.
I checked out is_int, but is_int('4') returns false.
I could use a cast/intval, but:
intval('6x') returns 6, and intval('x') returns 0 as does intval(0) and intval('0')

2
  • function f ($i) { return "$i" === "".(int)$i; } Commented May 16, 2014 at 17:41
  • Nice one, but i would prefer a more native solution, with documentation and whatnot. Commented May 16, 2014 at 17:51

2 Answers 2

7

Use filter_var():

if (filter_var('1', FILTER_VALIDATE_INT)) {
     echo 'int'."<br>";
}
if (!filter_var('dog', FILTER_VALIDATE_INT)) {
     echo 'not int'."<br>";
}

Demo

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

Comments

-2

The function is_int() is what you should use.

The reason why

is_int('4')

will return false is because it's not an integer. When you add quotes around the integer PHP will assume it's a string - hence the "false" return.

Try this out:

is_int(4)

4 Comments

Thanks, but the whole point is to check if a string is an int.
A string is not an integer, that's just a basic datatype fact. Do you want to check if a string CONTAINS an integer?
No, a string is not an integer.But I want to check if a given string can be safely converted into an int.
Alright, then you should listen to @John Conde. Good luck! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.