Why do I always get 0?
The problem is related to ctype_digit ()
Check out this example
<?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
ctype_digit($integer); // false (ASCII 42 is the * character)
this happens in your case as well, because 2 is the ASCII value for another non-numeric character and if () returns false in your case.
If you want to check if a string or digit is actually an int, you should use is_numeric()
and your code will become:
$number = 0;
if (isset($_GET['number'])) {
$temp_var = $_GET['number']; // 2
if (is_numeric($temp_var)) {
$number = (int)$temp_var; // 2
}
}
print $number; // 2
NOTE FROM MANUAL ON ctype_digit () :
This function expects a string to be useful, so, for example, passing an integer may not return the expected result. However, also note that HTML forms will contain numeric strings, not integers. See also the section on guide types.
If an integer between -128 and 255, inclusive, is specified, it is interpreted as an ASCII value for one character (negative values have 256 appended to allow characters in the extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.
PLUS:
if someone REALLY ABSOLUTELY MUST use ctype_digit (), for security reasons you can use this:
ctype_digit((string) $value);
this way you will ALWAYS be sure that it $value
is a string, and if it only consists of numeric characters, then ctype_digit will evaluate to true;)
source to share
Is it defined $fid
?
if (ctype_digit($fid)) {
You want to say:
if (ctype_digit($temp_var)) {
You provided an invalid parameter $fid
which was undefined. $fid
is not set such that the condition is false and does not go to if (ctype_digit($fid)) {}
, so the result shows that you originally defined$number
This is why you always received 0
.
EDIT
My answer was based on a previous version of the question.
Custom poster changed the content of the question.
I think it is not our fault if some body thinks our answers are inappropriate.
source to share