Skip to content

Instantly share code, notes, and snippets.

@AmyStephen
Created Oct 7, 2013
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@btopro btopro commented Oct 7, 2013

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

@KimPrince

This comment has been minimized.

Copy link

@KimPrince KimPrince commented Oct 7, 2013

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

@ghost

This comment has been minimized.

Copy link

@ghost 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