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).
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);
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);
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…