Why do I always get 0?

I am sending a request to file.php

with a url like this:file.php?number=2

file.php:

$number = 0;
if (isset($_GET['number'])) {
    $temp_var = $_GET['number']; // 2
    if (ctype_digit($temp_var)) {
        $number = (int)$temp_var; // 2
    }
}   
print $number; // 0

      

I get 0 (zero) as an answer. Why?

+3


source to share


3 answers


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;)

+7


source


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.

+1


source


Try:

$number = 0;
if (isset($_GET['number'])) {
  if (is_numeric($_GET['number'])) {
    $number = (int)$_GET['number'];
  }
}   
print $number; 

      

Edited the following answer above to use is_numeric is a much better idea

0


source







All Articles