Prince Prince - 6 months ago 15
PHP Question

Check if the value is an integer in PHP

I am working on a project and in that project I have two objectives

  1. I receive data from user

  2. I check if the data sent by the user is an
    or in case is an integer, if is less than 1

So I wrote this code

<form action="" method="get">
<input type="text" name="quantity" value="2"/>
<input type="submit"/>

if (!is_int($_GET['quantity']) || $_GET['quantity'] < 1){
$_GET['quantity'] = 1;

echo $_GET['quantity'];

The problem, I am facing is that, the program always echo
even if the data is less than 1 or is not an integer at all.

Help me solve this problem please


Try replacing

if (!is_int($_GET['quantity']) || $_GET['quantity'] < 1){


$quantity = (int) $_GET['quantity'];

if ($quantity < 1) {...}

This casts it to an integer, and if not an integer, casts it as being assigned 0. Then it compares whether it is < 1 or not, and should have the desired result that you are looking for.