PHP if single or double equals

2020-02-07 05:05发布

问题:

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)

回答1:

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.



回答2:

The identical to operator, ===, is used when you want to compare two operands' values and types.

The equal to operator, ==, is used when you want to compare two values. It will evaluate to true if both values are equivalent (i.e. 15 == "15" would be true).

The assignment operator, =, is used to assign a value to a variable. This operator should not be used for comparing values; that is not what it is for.

Now, for comparing strings in various ways you may want to look at the strcmp family of functions. They are very useful for comparing strings in a variety of ways.



回答3:

$a === $b   TRUE if $a is equal to $b, and they are of the same type.

More info: http://www.php.net/manual/en/language.operators.comparison.php