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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With