Home  >  Article  >  Backend Development  >  Analyze the difference between i++ and ++i in PHP

Analyze the difference between i++ and ++i in PHP

*文
*文Original
2018-01-02 11:40:332023browse

This article mainly introduces relevant information that briefly analyzes the difference and efficiency between i++ and ++i in PHP. It is very good and has reference value. Friends in need can refer to it. I hope to be helpful.

Let’s look at the basic differences first:

i++: First use the current value of i in the expression where i is located, and then add i 1

++i: Let i add 1 first, and then use the new value of i in the expression where i is located

Watch some video tutorials When writing a for loop, always write ++i instead of i++. After searching on the Internet, it turns out that there is an efficiency issue

++i is equivalent to the following code


i += 1; 
return i;

i++ is equivalent to the following code


j = i; 
i += 1; 
return j;

Of course, if the compiler will optimize out these differences, then the efficiency will be almost the same.

Let me tell you the difference between ++i and i++ in detail

1. The usage of ++i (with a =++i, i=2 for example)

First add 1 to the i value (that is, i=i+1), and then assign it to variable a (that is, a=i),

Then the final a value is equal to 3, and the i value is equal to 3.

So a=++i is equivalent to i=i+1, a=i

2, usage of i++ (take a=i++, i=2 as an example)

First assign the i value to the variable a (that is, a=i), then add 1 to the i value (that is, i=i+1),

Then the final a value is equal to 2, i value is equal to 3.

So a=i++ is equivalent to a=i, i=i+1

3, ++i and i++

a=++ i is equivalent to i++, a=i

a=i++ is equivalent to a=i, i++

##4, ++i and i++ are equivalent to i=i+ when used alone 1

If assigned to a new variable, ++i first adds 1 to the i value, and i++ first assigns i to the new variable.

Related recommendations:

php Efficient string processing method

PHP basic algorithm

php basic function

The above is the detailed content of Analyze the difference between i++ and ++i in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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