【问题标题】:Conditional in PHP not working correctlyPHP中的条件无法正常工作
【发布时间】:2013-04-03 16:05:56
【问题描述】:

我的条件基本上是这样的:

如果类型为 5,并且用户状态未登录或历史计数为 0(或两者均为真 - 用户未登录且历史计数为 0),则执行某些操作(在这种情况下,跳过以下循环处理并跳转到下一个迭代器)。

我做错了什么,因为它会影响 else,即使我认为不应该这样做。

代码如下:

if($row['type'] === 5 && ($_SESSION['appState']['user_state']['status'] <> STATE_SIGNED_IN ||  $historyRtn[0]['historyCnt'] === 0) ) {
    error_log("don't create");
    continue;
}
else {
    error_log("type: " . $row['type'] . "; appState: " .$_SESSION['appState']['user_state']['status'] . "; historyCount: " . $historyRtn[0]['historyCnt']  );
}

对于 $row['type'] 为 5 的所有代码块,无论其他值是什么,它都会触发 else。这是来自 else 的错误日志。 (仅供参考,STATE_SIGNED_IN 设置为“已登录”。)

// this one incorrectly hits the else, as appState is not signed in and historyCount is 0
type: 5; appState: recognized unregistered; historyCount: 0  

// this one incorrectly hits the else, as appState is signed in, but historyCount is still 0
type: 5; appState: signed in; historyCount: 0

// this one correctly hits the else, as appState is signed in and historyCount is 1
type: 5; appState: signed in; historyCount: 1

如果三个条件都为真,我需要如何表达 if 语句,以便它只命中 else?我宁愿不更改声明是否类型为 5 并且 appState 已登录并且 historyCount > 0 因为它需要一个 else (我现在只有 else 用于测试)并且它需要移动所有其余的在 else 中运行的循环代码 - 如果我可以评估我不希望循环在 if 中运行的条件,我可以使用 continue 仅跳过我不想处理的项目。

【问题讨论】:

  • 你确定你的意思是===?如果它来自数据库,很可能会以字符串的形式返回给您。
  • 尝试打印不同的条件变量,看看你的错误在哪里
  • @Adidi - 我正在打印不同的变量 - 这就是错误日志行。
  • @EmmyS,您正在打印他们的字符串表示。考虑使用var_dump
  • 是的,@zneak - 这就是问题所在 - 它们以字符串的形式返回。一旦我将=== 更改为==,它就可以正常工作了。

标签: php conditional


【解决方案1】:

由于您使用的是===,因此您是在询问$row[type] 是否等于5,并且它们属于同一类型。你需要做一个var_dump$row 来查看数据类型是什么。

例如:

$row[type] = "5";
var_dump($row[type]);

返回

string(1) "5"

因此,这些类型可能不会评估为 true。

你可以尝试像这样投射:

if( (int)$row[type] === 5 ... )

【讨论】:

  • 是的,谢谢 - 我真的不需要投射,我不认为;我可以测试一下$row['type'] == 5
【解决方案2】:

在你的代码中

if($row['type'] === 5 && ($_SESSION['appState']['user_state']['status'] <> STATE_SIGNED_IN ||  $historyRtn[0]['historyCnt'] === 0) )

您使用的是=== 运算符而不是==

=== 将匹配值和类型

== 只会匹配值

所以要么用户== 要么检查类型是否相等

【讨论】:

    猜你喜欢
    • 2012-01-27
    • 2013-07-18
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多