Skip to content

Instantly share code, notes, and snippets.

@AmyStephen
Created October 7, 2013 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmyStephen/6876184 to your computer and use it in GitHub Desktop.
Save AmyStephen/6876184 to your computer and use it in GitHub Desktop.
How do you determine if a value is an Integer?
<?php
// Case 1 Produces:
// int_of_value: 0 is equal to value: dog
$value = 'dog';
$int_of_value = (int) $value;
if ($int_of_value == $value) {
echo 'int_of_value: ' . $int_of_value . ' is equal to value: ' . $value;
} else {
echo 'int_of_value: ' . $int_of_value . ' is NOT equal to value: ' . $value;
}
// Case 2 Produces:
// int_of_value: 0 is NOT equal to value: dog
$value = 'dog';
$int_of_value = (int) $value;
if ($int_of_value === $value) {
echo 'int_of_value: ' . $int_of_value . ' is equal to value: ' . $value;
} else {
echo 'int_of_value: ' . $int_of_value . ' is NOT equal to value: ' . $value;
}
// Case 3 Produces:
// int_of_value: 0 is NOT equal to value: dog
$value = '0';
$int_of_value = (int) $value;
if ($int_of_value === $value) {
echo 'int_of_value: ' . $int_of_value . ' is equal to value: ' . $value;
} else {
echo 'int_of_value: ' . $int_of_value . ' is NOT equal to value: ' . $value;
}
// Case 4 Produces:
// int_of_value: 0 is equal to value: 0
$value = 0;
$int_of_value = (int) $value;
if ($int_of_value === $value) {
echo 'int_of_value: ' . $int_of_value . ' is equal to value: ' . $value;
} else {
echo 'int_of_value: ' . $int_of_value . ' is NOT equal to value: ' . $value;
}
// Case 5 Produces:
// no
$value = '0';
if (is_integer($value)) {
echo 'no';
} else {
echo 'yes';
}
// Case 6 Produces:
// yes
$value = 0;
if (is_integer($value)) {
echo 'no';
} else {
echo 'yes';
}
@btopro
Copy link

btopro commented Oct 7, 2013

for additional confusion you could also try ctype_digit http://php.net/manual/en/function.ctype-digit.php :)

@KimPrince
Copy link

What's wrong with if ((is_int($value)) || ctype_digit($value)) { ... }

Copy link

ghost commented Oct 23, 2013

Hi Amy. :)

How about :

        if ( filter_var ( $value , FILTER_VALIDATE_INT )){

            echo 'Bark like a dog';

        }


What not to do

Many people will be tempted to use one or more of the following when faced with validating integers:

Cast the input to INT
Use ctype_digit()
Use is_numeric() 

These are all the wrong ways to approach this problem.

So, how do I fix it?


^ info from here -> http://wiki.hashphp.org/Validation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment