Created
October 7, 2013 22:37
-
-
Save AmyStephen/6876184 to your computer and use it in GitHub Desktop.
How do you determine if a value is an Integer?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} |
What's wrong with if ((is_int($value)) || ctype_digit($value)) { ... }
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
for additional confusion you could also try ctype_digit http://php.net/manual/en/function.ctype-digit.php :)