Hypister Hypister - 3 months ago 8
PHP Question

Natural number range issue

I need to check if the variable informed has only numbers between 1 and 10 to proceed with the code.

I've tried with many ways, using php native functions is_numeric, is_int, ctype_digit, regex and comparing to check if the variable value is in the range, but I ever have an issue.

My first attempt was with this:

if($quantity <= 0 || $quantity > 10)
{
redirect('page.php?msg=error');
exit();
}
else
{
//Ok, the value is 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10
}


But this code let's pass if the variable is, for example:
,1
or
00001
. PHP is_number allow decimals, is_int allow negatives, ctype_digit allows 000001 for example. I tried all, and I think I will can achieve this only using regex. I've tried with
/^[0-9]/
but only the first digit gets affected. How to allow only the natural numbers between 1 and 10?

Answer

If $quantity comes from external input, such as $_POST, $_GET, $_REQUEST, or $_COOKIE it's always going to be parsed as a string. You can use filter_input to ensure your inputs are converted to the appropriate type.

For example, let's say you get this value from $_POST["quantity"] and you want to insure it's always a valid integer value between 1 and 10.

if ($quantity = filter_input(INPUT_POST, "quantity", FILTER_VALIDATE_INT, ["options" => ["min_range" => 1, "max_range" => 10]])) {
    // It's a valid value from 1 to 10
} else {
    // It's not a valid value we expect :(
}

Here are some test cases to demonstrate that it does what you want...

$values = [1, 0, 10, 11, '1', '0', '10', '11', '001', ',1'];

$opts = ["options" => ["min_range" => 1, "max_range" => 10]];

foreach($values as $value) {
    if ($quantity = filter_var($value,FILTER_VALIDATE_INT, $opts)) {
        echo "\$quantity = $quantity which is VALID!\n";
    } else {
        echo "\$quantity = $value which is NOT valid :(\n";
    }
}

This should give you...

$quantity = 1 which is VALID!
$quantity = 0 which is NOT valid :(
$quantity = 10 which is VALID!
$quantity = 11 which is NOT valid :(
$quantity = 1 which is VALID!
$quantity = 0 which is NOT valid :(
$quantity = 10 which is VALID!
$quantity = 11 which is NOT valid :(
$quantity = 001 which is NOT valid :(
$quantity = ,1 which is NOT valid :(
Comments