is_int and GET or POST - php

Why does is_int always return false in the following situation?
echo $_GET['id']; //3
if(is_int($_GET['id']))
echo 'int'; //not executed

Why does is_int always return false?
Because $_GET["id"] is a string, even if it happens to contain a number.
Your options:
Use the filter extension. filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT) will return an integer typed variable if the variable exists, is not an array, represents an integer and that integer is within the valid bounds. Otherwise it will return false.
Force cast it to integer (int)$_GET["id"] - probably not what you want because you can't properly handle errors (i.e. "id" not being a number)
Use ctype_digit() to make sure the string consists only of numbers, and therefore is an integer - technically, this returns true also with very large numbers that are beyond int's scope, but I doubt this will be a problem. However, note that this method will not recognize negative numbers.
Do not use:
is_numeric() because it will also recognize float values (1.23132)

Because HTTP variables are always either strings, or arrays. And the elements of arrays are always strings or arrays.
You want the is_numeric function, which will return true for "4". Either that, or cast the variable to an int $foo = (int) $_GET['id']...

Checking for integers using is_int($value) will return false for strings.
Casting the value -- is_int((int) $value) -- won't help because strings and floats will result in false positive.
is_numeric($value) will reject non numeric strings, but floats still pass.
But the thing is, a float cast to integer won't equal itself if it's not an integer. So I came up with something like this:
$isInt = (is_numeric($value) && (int) $value == $value);
It works fine for integers and strings ... and some floating numbers.
But unfortunately, this will not work for some float integers.
$number = pow(125, 1/3); // float(5) -- cube root of 125
var_dump((int) $number == $number); // bool(false)
But that's a whole different question.

How i fixed it:
$int_id = (int) $_GET["id"];
if((string)$int_id == $_GET["id"]) {
echo $_GET["id"];
}

It's probably stored as a string in the $_GET, cast it to an int.

Because $_GET is an array of strings.
To check if the get parameter contains an integer you should use is_numeric()

Because $_GET['id'] is a string like other parts of query string. You are not converting it to integer anywhere so is_int return false.

The dirty solution I'm using is this:
$val = trim($_GET['id']);
$cnd = ($val == (int)$val);
echo $cnd ? "It's an int" : "Not an int";
Apart from the obvious (ugly code that hides its workings behind specifics of the php engine), does anybody know cases where this goes wrong?

Prabably best way to check if value from GET or POST is integer is check by preg_match
if( preg_match('/^[0-9]+$/', $_GET['id'] ){
echo "is int";
}

You can possibly try the intval() which can be used to test the value of your var. e.g
If(intval($_GET['ID']==0)
The function will check if the var is integer and return TRUE if not FALSE

Related

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.
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.
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.

Multiple PHP IF conditions not working

I am trying to make sure the GET string is set in the URL and that it's value is an integer, but I can't get this to work.
if (isset($_GET['allusers']) && is_int($_GET['allusers'])) {
echo "works";
}
Am I doing something wrong with my parentheses?
A $_GET variable can't be an integer. It'll always be a string.
To test is it's a numeric string, use is_numeric():
if ( isset($_GET['allusers']) && is_numeric($_GET['allusers']) )
{
echo "works";
}
In your code
isset($_GET['allusers'])
will be evaluated to be true but
is_int($_GET['allusers']) will not as the value of $_GET is a string not int you can modify your code as
if (isset($_GET['allusers']) && is_int(intval($_GET['allusers']))) {
echo "works";
}
This will work
Use ctype_digit if you are expecting only non-negative integers. This will give the best result in those cases since it allows only the numbers 0-9.
Note that is_numeric will return true for strings which can be converted to integers, both negatives and floats. A few examples of what is_numeric will consider to be true:
0xF5 (hexadecimal)
-.0e-000 (a strange way of expressing 0.0)
-0.4
is_int returns false on a string, which is what a GET variable will be.
var_dump(is_int("23"));
bool(false)
You should be using is_numeric instad.

Checking that the get value is an integer (whole number)

I'm currently building a room booking system and was wondering how to check if the user has correctly entered an integer i.e. 0,1,2,3,4,5 on the form and not anything else (i.e. left it blank, entered decimal number or alphabet).
$capacity = $_GET["capacity"];
Thanks in advance!
As per comments check the post variable is set first, else a warning is raised in recent PHP versions:
isset($_GET['capacity'])
Hence, you can:
Cast it to an int:
$capacity = isset($_GET['capacity']) ? (int)$_GET['capacity'] : null
Use a function:
$capacity = is_numeric($_GET['capacity']) ? (int)$_GET['capacity'] : null;
// cast to int as is_numeric will return floats too
Make it a number and compare against original input:
$capacity = ((int)$_GET['capacity']) == $_GET['capacity']) ? $_GET['capacity'] : null;
This last is ideal in situations where the input might exceed MAX_INT or be altered by casting in some other way.
preg_match('/^[0-5]$/', $_GET['capacity']);
If not just limited from 0 to 5,
preg_match('/^[0-9]+$/', $_GET['capacity']);
this is a filtering job, so a good option is to use the filter module (http://php.net/filter)
so you might use filter_var or filter_input with FILTER_VALIDATE_INT as a flag and compare the result to false (strict comparison, to avoid confusion caused by 0)
I have a different approach if you like:
$validValues=array('0','1','2','3','4','5');
$capacity = $_GET["capacity"];
$isValid=in_array($capacity,$validValues); //TRUE if entered value is in the valid values.
Values read from the $_GET are strings anyway.
PHP manual: in_array()
Check out is_numeric function.
Use regular expression to match for a whole number
preg_match('/^[0-9]\d*$/', $variable)
if($_GET["capacity"] >= 0 && $_GET["capacity"] < 5)
{
//prefect
}
else
{
//invalid
}

How to compare string or int type?

if($_GET['choice'] == (int))
or
if($_GET['choice'] == (string))
I got an error.
All GET parameters are strings. If you want to be certain that it's an integer in the string then you should sanitize it.
To check if the string $_GET['choice'] may be represented as an integer, use ctype_digit(), eg
if (ctype_digit($_GET['choice'])) {
// integer
}
You're doing it wrong. Your example shows CASTING:
$var = (int)"15"; // casts the string 15 as an integer
If you want to compare if something is an INTEGER, you can use the is_int() function in PHP. There are other operators that will do this for strings, arrays, etc;
http://us2.php.net/manual/en/function.is-int.php

How to check in PHP if a string can be transformed to integer?

I have strings of the following form: "37", "42", "7".
I need to transform them into integers. I can use intval. But I want to check if the string was in the expected format (by not expected format I mean, for example, "abc" or "a7"). How can I do it before or after use of the intval?
As far as I know intval returns 1 if the argument was not in the appropriate format. If it is the case, there is not way to check if the argument was the good format just by analyzing the output of the intval.
You can use
ctype_digit()
http://ro2.php.net/ctype_digit
You're probably looking for filter_var.
$input = '5';
filter_var($input, FILTER_VALIDATE_INT); // returns 5
$input = 'asdf';
filter_var($input, FILTER_VALIDATE_INT); // returns false
There are also many other options you can pass into this function. I believe it was designed as a way to validate form submissions.
ctype_digit($x) && ($x == floor($x))
You can use the function is_numeric(). It should return true if it is a number, false if there are letters in the mix.
Mediocre solution, but you could do:
preg_match('/^[0-9]*$/', $value)
How about (int)$value == $value?
This would cast the value to an int, so that the left hand is definately an integer, and then checks if an untyped comparison is true.

Categories