I need to take a string and return true if only positive OR negative numbers are in the string. Is there a way to do this?
$rating = "-25";
if (!ctype_digit($rating)) {
echo "Not a digit.";
}
else {
echo "Is a digit.";
}
Result:
Not a digit.
Need Result:
Is a digit.
ctype_digit()
works on values that consists only of digits. Where $rating = -25;
is false as it is being treated as a ASCII code in this particular case (explained below), and "-25"
is invalid because -
is not a digit. You could type juggle but I think you're looking for is_numeric()
echo is_numeric( "-25");
or echo ctype_digit((integer) $var);
However the latter would return true if the string cannot be cast to an integer. It will have the value of 0 if that's the case.
Important: If you pass a literal integer in range of -128
and 255
to ctype_digit()
the value is converted to the character defined in the ASCII table. If its not a number, false is expected. Any other integer value is normal expected behavior.