为什么PHP执行条件块,零和空相关

时间:2019-01-07 05:26:03

标签: php

我的php变量分配了3个可能的值,具体取决于$ _POST变量的值。可能的值为“是”,“否”和0(零)。我试图将0转换为null值,但最终也将'YES'和'NO'值也转换为null。

echo $used; 
//outputs: YES

echo gettype($used);
//outputs: string

//so far it works fine

if($used == 0)
{
    $used = null;
}

echo $used; 
//outputs:

echo gettype($used);
//outputs: null

//So it converted my variable to null.

//I could probably try a workaround by doing
if($used != 'YES' && $used != 'NO')
{
    $used = null;
}

//or maybe even using =='0' in the conditional but I prefer to learn why this is happening before moving forward

我发现 How to disable status bar click and pull down in Android? 看来我的问题可能出在== 0,但我不确定。预先谢谢你。

3 个答案:

答案 0 :(得分:3)

在处理多种类型时,

始终使用相同运算符而不是 quality 运算符。

相同是当您与===

进行比较时

等于是当您与==

比较时

仅当您100%确定要处理一种类型时,才检查是否相等。

if ($used == 0) { $used = null; } // Not like this
if ($used === 0) { $used = null; } // .. but like this

答案 1 :(得分:1)

0NULL都被视为false ...,而'YES'和'NO'字符串被视为true

那么为什么不找$used == 0呢?

编辑: 我知道我错误地读了您的问题,您使用的是==运算符,因此,作为integer的YES / NO为0。因此,在您的情况下,请先明确查找数值,请参见下文:

示例:

echo $used; 
//outputs: YES

echo gettype($used);
//outputs: string

// Now explicitly look for numeric values, and compare the integer
if(is_numeric($used) AND (int)$used === 0) $used = null;

答案 2 :(得分:1)

这已经在here中进行了讨论。

之所以发生这种情况,是因为“ YES”或“ NO”或任何其他字符串无法从字面上转换为整数值。

因此,当转换除“ 123”以外的任何字符串或任何双引号的字符串时,将变为false。这就是为什么您的代码 $ used == 0 会变为true。

$ YES-> false-> 0 ==0。

如果要将0替换为null,我当前的解决方法是if(is_int($ used)),因为只有0可以捕获。

我希望能解决。谢谢。

更新:使用“ ===”代替“ ==”

相关问题