Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$_POST not getting number zero

Tags:

html

post

php

I have the following code inside a form whereby when press submit button, php side is grabbing the input value using $_POST['revisionCad'].

<form method="POST">
    <input type="number" class="form-control" placeholder="Revision" name="revisionCad" id="revisionCad" min="0">

    <button name="submit" class="btn btn-primary" id="submit" tabindex="5" value="Save" type="submit" style="width:200px;">Create/Change Revision</button>
</form>

My Issue

Everything working fine except when I gave number 0 as input, $_POST is getting no value. My error check telling, please enter a number. Below is my error check code

if(isset($_POST['revisionCad'])){
    $revisionCad = $_POST['revisionCad'];  
}

if(empty($revisionCad)){
    erDisplay('Please select a revision for Cadgui');
}

But any number greater than 0, $_POST['revisionCad'] is grabbing correctly. I tried to remove the min attribute as well as change to -1. But still whenever I enter number 0, $_POST['revisionCad'] not grabbing any value. Anyone knows why?

like image 385
Anu Avatar asked Oct 20 '25 20:10

Anu


1 Answers

To explain why this is happening, you have to take a closer look at the PHP empty() function. From the documentation we see that (emphasis mine)...

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE.

In PHP, the value of zero is a falsy value. So you get the following output,

var_dump(false == 0); // Outputs "true"
var_dump(empty(0));   // Outputs "true"

So you need to alter your code to check if the variable is set and greater or equal to zero, which you can do by altering the snippet you showed to the following.

if (isset($_POST['revisionCad']) && $_POST['revisionCad'] >= 0) {
    $revisionCad = $_POST['revisionCad'];
} else {
    erDisplay('Please select a revision for Cadgui');
}
  • http://php.net/empty
like image 101
Qirel Avatar answered Oct 22 '25 12:10

Qirel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!