Validating whether $_REQUEST contents is an int - php

I am trying to do a basic operation: to check whether string is a number.
This does not work:
$qty = $_REQUEST[qty];
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
This one does:
$qty = 1;
if (is_int($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
$_REQUEST[qty] is posted with AJAX request ($.post). $_REQUEST[qty] is NOT empty and contains only number (1).
is_numeric() is not going to work, since it treats 1e4 as a number.

is_int will only return true if the variable is of integer type.
if you are trying to test if the variable contains a string which represents a number,
use:
is_numeric("1");
source: http://php.net/manual/en/function.is-int.php
EDIT:
use ctype_digit() to check for every character in the string if it's a number to rule out "1e4"

If you want to check for the presence of digits only, you can use ctype_digit .

try "is_numeric()" instead of "is_int"...
i think that u r getting a String from your Request...
and is_int really checks wether a given object is a integer... But it isn't -> it's a String.
is_numeric just checks, wether a object is convertable into an integer. If so, it returns true, otherwise false...
$qty = $_REQUEST[qty];
if (is_numeric($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
PS: Use $_POST[] or $_GET[] insetead of $_REQUEST[] ;)

You mention you cannot use is_numeric because it treats 1e4 as a number. Well, 1e4 is a number. Specifically 1 * 10^4.
You could use is_int(intval($_REQUEST['qty'])), but as intval always returns an int (0 on failure or empty input) you run the risk of false positives. However, combined with is_numeric or filter_var you should be on pretty solid ground.

Actually, all $_REQUEST (as well as $_GET, $_POST, etc) values are always strings.
When $qty is $_REQUEST[qty] it's an string, not an integer. When $qty is 1, it's already an integer.
Use intval function to convert it to an integer. But as you say, you only want to find out whether it's an integer or not, so use floatval to convert it, then check if they are equal:
if (intval($qty) == floatval($qty)) {
echo "Ok!";
} else {
echo "error";
}

Do a not-identical comparison­Docs while using the string and integer cast:
if ($qty !== (string)(int)$qty) {
echo "error";
} else {
echo "ok";
}
This is basically literal: As all incoming variables are strings, you can't check them being an integer, unless you cast them to an integer and then back to string. Wrap it into a function if it's to hard to grasp in inline code what it does:
/**
* string is integer value?
*
* #return bool
*/
function is_int_string($string)
{
return $string === (string)(int)$string;
}
$qty = $_REQUEST[qty];
if (is_int_string($qty) == FALSE) {
echo "error";
} else {
echo "ok";
}
HTTP is a text protocol, so there is only string in the beginning.

I decided to go with preg_match().
if (!preg_match("/^[0-9]+$/", $_REQUEST[qty])) {}

Related

How to determine the type of a numerical value passed as a string without losing data or being converted to wrong datatype

I want to allow users to submit numerical values through an online form but I've ran into a problem trying to validate the correct datatype(integer or float) for the submitted value.
Lets say a user submits:
3.14
I cannot use is_float() because the user-value is technically a string.
floatval() would work, except when the user only supplies an integer floatval() still considers it a float instead of an integer.
gettype(floatval("3"))
returns float, but I need it to return integer.
I even tried checking if it was an integer like this:
is_int(floatval(3)) // returns false
But why does the above return false?
The below prints 3 as if it was an integer:
echo floatval(3)
Therefore, I need a function that can be able to tell the difference between a float and integer passed as a string so it doesn't
pass an integer off as a float.
doesn't truncate a float into an integer.
Pattern checking with regular expressions could possibly be a solution, but are there any other alternatives?
NOTE: I am not using classes or objects and I prefer not to if possible.
Convert it to a float and integer, then check if they're equal.
$i = intval($input);
$f = floatval($input);
if ($i == $f) {
$type = "int";
} else {
$type = "float";
}
Below function will solve your problem
function checkType($inputNumber){
if (strpos($inputNumber, '.') !== false) {
return 'Number is float';
} else {
return 'Number is integer';
}
}
echo checkType(3.5); o/p Number is float.
echo checkType(3); o/p Number is integer.
First of all, If you checking float then obviously it will only return true or false on float value weather or not it's a integer.
You are checking for float then how can you expect that it will return integer. Use intval() to check integer value.
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
Or you can do one thing you can check if dot(.) exist then check with floatval() and not then check with intval()
You can alos do something like following
<?php
$a = '1.6';
if(str_pos($a, '.') !== 'false){
$a = intval($a);
}else{
$a = floatval($a);
}

PHP - if condition match exact value including decimal

i am trying to match exact number with decimal. i have tried following but doesn't work
tried following code, but doesn't work with decimal.
<?php
$number=1.23;
$numbers=1.28;
if (is_float($number)==is_float($numbers))
{
echo 'matched';
}else{
echo 'not matched';
}
?>
please check where i am doing mistake or it's totally wrong way to do that. i have check above in PHP sites.
Use floatval (which returns the float value of the given variable) instead of is_float (which returns true if the given variable is a float and false if it isn’t).
You could simply make use of a strict matching operator === instead of floatval or is_float.
<?php
$number=1.23;
$numbers=1.28;
if($number === $numbers)
{
echo "Matched";
}
else { echo "No Match"; }

Int or not Int. How to fix the code?

I would like the code below to return 'Int' the first time and 'Not int' the second time. Unfortunately it returns 'Not int' twice instead.
How can I fix this?
<?php
$test1='1';
if(is_int($test1)){
echo "Int";
}else{
echo "Not int";
}
echo "\n";
$test2='1a';
if(is_int($test2)){
echo "Int";
}else{
echo "Not int";
}
?>
By wrapping the number in quotation marks '1', you are declaring a string.
Instead you got to use $test1 = 1;.
By using the PHP ctype_digit() function, you can check if a string only contains digits.
You could also use the is_numeric() function, which also returns true if the string contains a exponential part like +0123.45e6 or a hex value 0xFF.
is_int - Find whether the type of a variable is integer
Because you put the number in quotes, it is a string. Therefore is_int = false
is_numeric — Finds whether a variable is a number or a numeric string
Because the string is actually a number, is_numeric will return true
So, change is_int to is_numeric and it works:
<?php
$test1 = '1';
if (is_numeric($test1))
{
echo 'Int';
}
else
{
echo 'Not int';
}
echo "\n";
$test2 = '1a';
if (is_numeric($test2))
{
echo 'Int';
}
else
{
echo 'Not int';
}
?>
Use ctype_digit() instead.
ctype_digit('1'); // True
ctype_digit('1a'); // False
change
$test1='1';
to
$test1=1;

How can one check in PHP if a string can be converted into a whole number?

For instance, "000", "404", and "0523" can be converted into whole numbers in PHP, but "42sW" and "423 2343" cannot be converted into whole numbers.
Use the ctype_digit function. is_numeric will also permit floating point values.
$numArray = array("1.23","156", "143", "1w");
foreach($numArray as $num)
{
if (ctype_digit($num)) {
// Your Convert logic
} else {
// Do not convert print error message
}
}
}
PHP's is_numeric() can determine if a given param is a number or a number string. Have a read through the manual for some examples.
ctype_digit should be what you're looking for.
42Sw can be converted to a number by using intval()
echo intval("42sW"); // prints 42
use is_numeric():
if (is_numeric("string")) {
echo "This can be converted to a number";
}
You could try something like this.
<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>
$test = "42sW";
if (ctype_digit($test)) {
echo "The string $test consists of all digits.\n";
} else {
echo "The string $test does not consist of all digits.\n";
}
//OR
is_numeric($test); // false

is_int and GET or POST

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

Categories