Search code examples
phpnulluser-input

Check Empty and zero on PHP


I want to add subtract and other function from user data in PHP. At first, I want to check the field is empty or not.When I check empty using empty() function and I submit zero then it shows required that means it is empty.How can I input zero and it add or subtract with my second value?Thank you.My code is here

<html>
<head>

</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $num1=$_POST['num1'];
    $num2=$_POST['num2'];
    if (empty($num1 AND $num2)){
        echo "Required";
    }else{
    if ($_POST['submit']=='Add'){
        $num1=$_POST['num1'];
        $num2=$_POST['num2'];
        $add=$num1+$num2;
        echo $add;
    }
    elseif ($_POST['submit']=='Subtract'){
        $subtract=$num1-$num2;
        echo $subtract;
    }
    elseif ($_POST['submit']=='Multiplication'){
        $multiply=$num1*$num2;
        echo $multiply;
    }
    elseif ($_POST['submit']=='Division'){
        $division=$num1/$num2;
        echo $division;
    }

    }
}
?>

<form action="" method="post">
    <input type="number" name="num1">
    <input type="number" name="num2">
    <input type="submit" name="submit" value="Add">
    <input type="submit" name="submit" value="Subtract">
    <input type="submit" name="submit" value="Multiplication">
    <input type="submit" name="submit" value="Division">
</form> 

</body>
</html

Solution

  • change this line

     if (empty($num1 AND $num2)){}
    

    to

    if (isset($num1) && isset($num2)  && $num1>=0 && $num2>=0){}// this will show warning if $num1 or $num2 is not set
    

    or

    if (!empty($num1) && !empty($num2)  && $num1>=0 && $num2>=0){}// this will not show warnings
    

    empty will consider 0 as empty but if $num1 or $num2 is not set already this will not show any error