问题描述
为了检查一个字符串是否与另一个字符串匹配,我到目前为止一直在使用双等号。例如
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)
推荐答案
Double equals( ==
)可能就是您想要用于比较的内容。 (你也可以使用三等于ie ===
进行'严格'比较,这样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.)
单个等号是一个赋值:它会覆盖左侧,然后是,如果
语句只相当于检查被分配的值(例如右侧的值)。
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).
例如,这将打印它不是零!
后跟 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);
但这将打印它不是零!
然后是 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
设置 $ foo
设置为0,然后评估
as 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如果单或等于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!