Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Last active August 29, 2015 14:04
Show Gist options
  • Save jtpaasch/e8be6b749addfc547802 to your computer and use it in GitHub Desktop.
Save jtpaasch/e8be6b749addfc547802 to your computer and use it in GitHub Desktop.
A PHP function to check if a string is an integer
/**
* This function takes a string and tells you
* if the string represents an integer.
* All characters of the string must be digits,
* and there cannot be any leading zeros.
*
* @param String $string The string to check.
* @return Boolean
*/
function is_this_string_an_integer($string) {
// Assume from the start that the string IS an integer.
// If we hit any problems, we'll bail out and say it's NOT an integer.
$is_integer = true;
// Convert the string into an array of characters.
$array_of_chars = str_split($string);
// If there are no characters, we don't have an integer.
if (empty($array_of_chars)) {
$is_integer = false;
}
// If the first character is a zero, we don't have an integer.
// Instead, we have a string with leading zeros.
if ($is_integer && $array_of_chars[0] == '0') {
$is_integer = false;
}
// If we still think it might be an integer,
// step through each char and see if it's a legitimate digit.
if ($is_integer) {
foreach ($array_of_chars as $i => $char) {
// Use PHP's ctype_digit() function to see if this
// character is a digit. If not, we can bail.
if (!ctype_digit($char)) {
$is_integer = false;
break;
}
}
}
// Finally, do we have an integer string or not?
return $is_integer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment