duancaozen6066 2017-04-13 08:25
浏览 62
已采纳

如何使用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?

  • 写回答

4条回答 默认 最新

  • duanjipiao7076 2017-04-13 08:33
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi