Home > Backend Development > PHP Tutorial > When writing a program, 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?

WBOY
Release: 2016-10-22 00:14:21
Original
1572 people have browsed it

What is the difference between $a == 2 and 2 == $a when making judgments when writing a program

Reply content:

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

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template