What is the difference between $a == 2 and 2 == $a when making judgments when writing a program
What is the difference between $a == 2 and 2 == $a when making judgments when writing a program
For languages that can assign values in conditional operators, placing constants before comparison operators can avoid problems caused by missing equal signs.
In other words, this can avoid the problem of writing $a == 2
as $a = 2
caused by our various mistakes.
This technique is not very useful in php, but it is more useful in java web. For example, to determine whether a certain parameter a submitted by the user is equal to the string "abc"
use "abc".equals(a)
Better than a.equals("abc")
, because a may be empty, the latter will report an error, but the former can give the correct result.
2==$a I have never seen this way of writing. If possible, could you please enlighten me?
It doesn’t have much effect.
The main purpose is to prevent missing an equal sign when making judgments.
Assume $a=1;
2==$a;//Can be executed, the value is false
2=$a;//Save
$a==2;//Can be executed, the value is false
$a= 2;//Can be executed, the value is true, because it is an assignment statement
$a == 2 If there is one less equal sign, the compiler will not prompt an error for the assignment operation.
2 == $a If there is one less equal sign, the compiler will prompt an error.
The premise is that it is placed in the if to perform the comparison operation.
There is no difference
However, $a == 2 is more acceptable in terms of semantics