PHP 如果 single 或 double 等于 [英] PHP if single or double equals
问题描述
为了检查一个字符串是否与另一个字符串匹配,我一直在使用双等号.例如
For checking if one string matches another I've been using double equals sign up to now. e.g.
if ($string1==$string2)
这是因为我使用的大多数字符串都是字母数字.但是现在我正在尝试用这样的数值做同样的事情:
This is because most of the strings I've been using are alphanumeric. However now I am trying the same thing with numeric values like this:
$string1 = 10;
$string2 = 10;
问题是,我是做单个等于还是双重等于以确保两个字符串 100% 匹配,而不是更多而不是精确
Questions is, do I do a single equal or a double equal to make sure the two strings match 100% not more not less just exact
我也是:
if ($string1==$string2)
或
if ($string1=$string2)
推荐答案
双等号 (==
) 可能是您想要用于该比较的内容.(您也可以使用三重等号,即 ===
进行严格"比较,这样 "2" === 2
将是假的.)
Double equals (==
) is probably what you want to use for that comparison. (You can also use triple equals i.e. ===
for 'strict' comparison, so that "2" === 2
will be false.)
单个等号是一个赋值:它覆盖左边,然后你的 if
语句就相当于检查最终被赋值的值(例如右边的值手边).
A single equals sign is an assignment: it overwrites the left hand side, and then your if
statement would be just equivalent to checking the value that wound up being assigned (e.g. the value of the right hand side).
例如,这将打印 It's not zero!
后跟 foo = 1
(如您所料):
For example, this will print It's not zero!
followed by foo = 1
(as you'd expect):
$foo = 1;
if ($foo == 0) {
print("It's zero!");
} else {
print("It's not zero!");
}
print("foo = " + $foo);
但这将打印 It's not zero!
后跟 foo = 0
(可能不是你期望的):
But this will print It's not zero!
followed by foo = 0
(probably not what you expect):
$foo = 1;
if ($foo = 0) {
print("It's zero!");
} else {
print("It's not zero!");
}
print("foo = " + $foo);
原因是在第二种情况下,$foo = 0
sets $foo
为0,然后if
被评估为 if($foo)
.由于 0
是一个假值,所以运行 else
语句.
The reason is that in the second case, $foo = 0
sets $foo
to 0, and then the if
is evaluated as if($foo)
. Since 0
is a false value, the else
statement is run.
这篇关于PHP 如果 single 或 double 等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!