如何使用PHP将零值视为真?

Here is my sample code:

$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
  echo 'true';
}
else{
   echo 'false';
}

If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled: 1. true when I pass any value having 0. 2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.

I also tried this:

if(!isset($issue_id)){
  echo 'true';
}
else{
   echo 'false';
}


if(!empty($issue_id) || $issue==0){
  echo 'true';
}
else{
   echo 'false';
}

The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?

The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?

if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}

please notice I used !== not !=. this is why:

0 == "" // true
0 === "" // false

See more at http://php.net/manual/en/language.operators.comparison.php


also if you are expecting number you can use

if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}

since is_numeric("") returns false

http://php.net/manual/en/function.is-numeric.php


Alternatively if you expect number good option is filter_var

if (isset($_POST["issue_id"]) {
   $issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
   if ($issue_id !== false) { 
   }
}

since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0

http://php.net/manual/en/function.filter-var.php

When you get data from a form, remember:

  • All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
  • All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.

This means that $_POST['issue_id'] will be the string '0', which is actually truthy.

If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);

if(isset($_POST['issue_id'])) {
  if($_POST['issue_id'] == 0) {
    echo "true";
  }
  else {
   echo "false";
  }
}

@Abdus Sattar Bhuiyan you can also full fill your two condition like below one:

<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0")  ? true : false : false;
if($issue_id){
  echo 'true';
}
else{
   echo 'false';
}