Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

if statement - 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;

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

So do I do:

if ($string1==$string2) 

or

if ($string1=$string2)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...