0

Since it doesn't really matter if we send '1' or 1 to MySQL, or in many other cases in PHP,

I find myself constantly checking like:

if(ctype_digit($val) || is_int($val)){
   // Pass
}

Basically I want to make sure it is an integer, but it doesn't matter if it's represented as string or int.

So I thought:

Maybe there is an equivalent PHP function that does both at the same time that I'm not aware of? please let me know if there is.

Community
  • 1
  • 1
J. Doe
  • 812
  • 1
  • 15
  • 33

1 Answers1

1

If you want to check only if the value is integer than:

if(intval($val) == $val){
// Pass
}

If you want to check value and type in one go, than:

if(intval($val) === $val){
// Pass
}
A J
  • 36
  • 4
  • You're right, the first method will work for anything as long as it's positive and smaller than PHP_INT_MAX, (so `$val = PHP_INT_MAX.'1'; if(intval($val) == $val)...` would still fail), thank you very much for the nice first part though. – J. Doe Feb 07 '20 at 02:15
  • You're wrong. My first method works for both positive and negative numbers. Yes, smaller than PHP_INT_MAX. But for PHP_INT_MAX even your own genuine method that you posted in your question - it don't work. Also your method don't work for negative numbers (when they are string type). – A J Feb 07 '20 at 02:25
  • Stackoverflow has been around and answering millions of questions for over 10 years. Virtually all basic questions are duplicates and should be closed rather than answered. – mickmackusa Feb 07 '20 at 02:46