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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀