Validate Integer in PHP

  • iftekhar
  • Jun 17, 2017
  • 0 comment
  • 655 Views
  • Print

Every now and then we need to check if the value of a variable is an integer or not. Recently I came across a forum thread where someone is trying to understand why his/her snippet is not giving the appropriate result that he/she is looking for. In other words, if the variable is an integer this function should return TRUE, otherwise it would return FLASE. Here is a scenario for your thoughts.

<?php
$userid = "12345";
if (is_int($userid)) {
   echo 'its an integer';
} else {
   echo 'its not an integer';
}
?>

Many user on that forum suggested that he/she should be using is_numeric function that will give him/her the result he/she might be looking for. This is how it worked.

<?php
$userid = "12345";
if (is_numeric($userid)) {
   echo 'its an integer';
} else {
   echo 'its not an integer';
}
?>

Indeed, it does work. However, what we need to understand is that when we assign the value of a variable within “”, PHP will consider the value as string, not an integer. One way to make the first snippet to work is to remove the quotation(“”) mark from the variable or declare the variable value to be an integer to begin with (then test it with is_int function). Here is how it works.

<?php
// use it without ""
$userid = 12345;
// or declare the variable type
$userid = (int) "12345";
if (is_int($userid)) {
   echo 'its an integer';
} else {
   echo 'its not an integer';
}
?>

Either way, is_int function should work as it should be. In my personal opinion though, I really don’t think anyone should be using quote to define an integer value. If you have to, go with declaring the variable type. You can also use the following method to test your variable.

<?php
$userid = 12345;
if (filter_var($userid, FILTER_VALIDATE_INT)) {
   echo 'its an integer';
} else {
   echo 'its not an integer';
}
?>

In this case, it really doesn’t matter if you user the quote or not. It will validate your variable as an integer. I hope you would find this post to be useful.

References: is_int, is_numeric, filter_var

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.