3

The following code works great until inQuantity receives a zero "0". Upon receiving a zero it evaluates it as empty and puts in a null instead of a "0". If "0.00" is entered it is evaluated as not empty.

$_POST['inQuantity'] = (!empty($_POST['inQuantity'])) ? $_POST['inQuantity'] : NULL;

the following code produces the same result

    if (empty($_POST['inQuantity'])) {
        $state = "empty";
    } else {
        $state = "full";
    }

when inQuantity is "0" the output of $state is "empty"

Anybody know why this is?

user2793447
  • 285
  • 2
  • 8
  • 1
    This is not a "failure" at all, it is simply how php (and most other languages) interpret a '0' value. It is well documented behaviour. You probably want this as condition instead: `(isset($_POST['inQuantity']))` – arkascha Apr 04 '14 at 06:12
  • Note that the mentioned duplicate speaks of any variable, whereas this is about values taken from GPC; the difference is that the unwanted `empty()` behaviour is limited to only `"0"`. – Ja͢ck Apr 04 '14 at 06:21
  • Thank you very much, newbie here, still seemed like a bug to me. – user2793447 Apr 04 '14 at 06:22
  • Although it's documented, using `empty()` in this case would be the wrong function to use as well :) – Ja͢ck Apr 04 '14 at 06:24
  • I would like to add that the example in the manual "// Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; " is a poor example for newbies – user2793447 Apr 04 '14 at 06:31

2 Answers2

5

You should not use empty in this case, because it is standard behaviour of empty to return true in these cases:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

Try to use isset():

$_POST['inQuantity'] = (isset($_POST['inQuantity'])) ? (float) $_POST['inQuantity'] : NULL;
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
Barif
  • 1,552
  • 3
  • 17
  • 28
1

Because empty('0') yields true you would have to be more specific as to what you consider to be empty; for example:

if (isset($_POST['inQuantity'])) {
    // The 'inQuantity' parameter was passed via $_POST
} else {
    // Not passed
}

You could consider an empty string to be, well, empty:

if (isset($_POST['inQuantity']) && strlen($_POST['inQuantity'])) {
    // The 'inQuantity' parameter was passed via $_POST
    // and contains at least one character (worst case, it's an array)
} else {
    // Not passed or empty
}

Another way is to use input filtering:

$quantity = filter_input(INPUT_POST, 'inQuantity', FILTER_VALIDATE_FLOAT, FILTER_NULL_ON_FAILURE);

if ($quantity !== null) {
    // value was passed and is a valid floating point value
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309