'Need ctype_digit to return true for negative numbers also

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.

php


Solution 1:[1]

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.

Solution 2:[2]

filter_var is the correct answer to this question and has been around since 5.2, according to the documentation.

filter_var will return filtered data or false if the string is not a valid integer.

var_dump(filter_var("1", FILTER_VALIDATE_INT) !== false);
var_dump(filter_var("0", FILTER_VALIDATE_INT) !== false);
var_dump(filter_var("-1", FILTER_VALIDATE_INT) !== false);

Result:

test.php:1:boolean true
test.php:2:boolean true
test.php:3:boolean true

Note that you must perform a comparison with false instead of logical ! otherwise it will fail when comparing with 0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Zhro