【问题标题】:Using logical Operator 'or' return always true使用逻辑运算符“或”返回始终为真
【发布时间】:2015-01-08 11:21:06
【问题描述】:

嘿,所以我在这里要做的是验证我的函数的两个来源是否设置了 $this->post["search"] 使用它或者是否设置了 $this->post["id"]使用 id,但不能同时使用:

($this->post["search"] or $this->post["id"])

如果我转储我得到一个布尔值,答案是正确的,为什么? 因此,如果我有一个像 sql 字符串这样的长字符串,我不想使用elseif,我想更像:

$this->sql->cell("select search_for('" . $this->post["search"] or $this->post["id"] . "') as response;");

【问题讨论】:

  • ($this->post["search"] or $this->post["id"]) 返回 truefalse 而不是比后数组元素的内容。即如果 $this->post["search"] 包含“找到我”,那么它是 true
  • 我想像问题一样在一行中使用,但似乎我需要使用 if/else
  • ($this->post["search"]?$this->post["search"] : $this->post["id"])如果至少提供了一个值,则返回任一值。 Using the PHP Ternary Operator

标签: php debugging logical-operators


【解决方案1】:

您可能应该根据设置传递控制流:

if ( isset($this->post["search"]) ) {
  // deal with search
} else if ( isset($this->post["id"]) ) {
  // deal with id
} else { 
  // gracefully reject dealing: nothing to do
}

顺便说一句,isset 为空字符串返回 true

$test = array( 'a' => '' );
var_dump(isset($test['a']));
//⇒ bool(true)

判断$_POST参数是否有值,使用:

!empty($_POST['id'])

希望对你有帮助。

【讨论】:

  • 请修改我的问题!所以我不想使用 elseif 我想知道为什么如果我转储 $this->post["search"] 或 $this->post["id"] 行我总是正确的?
猜你喜欢
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
相关资源
最近更新 更多