Saddam Hossain
Saddam Hossain

Reputation: 25

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

Upvotes: 0

Views: 3747

Answers (2)

Marcelo Agim&#243;vel
Marcelo Agim&#243;vel

Reputation: 1719

Let's use v Sugumar's answer and make it easier:

function emp($value){
  if (isset($value) && $value>=0 )
     return true;//has value
  else
     return false;//empty
}

Now you just have to use it:

if(emp($num1) and emp($num2)){
    //You typed a value, do something
}

Upvotes: 1

Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4038

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

Upvotes: 0

Related Questions