Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ++$i and $i++ in PHP?

Tags:

operators

php

What's the difference between ++$i and $i++ in PHP?

like image 987
Steven Avatar asked Nov 18 '09 13:11

Steven


People also ask

What is the difference between i ++ and I --?

i++ is known as post increment whereas ++i is called pre increment. i++ is post increment because it increments i 's value by 1 after the operation is over. Here value of j = 1 , but i = 2 . Here the value of i will be assigned to j first, and then i will be incremented.

What is $$ in PHP?

The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using the $ symbol before the $x value. These are called variable variables in PHP.

What is difference between and in PHP?

The difference is, strings between double quotes (") are parsed for variable and escape sequence substitution. Strings in single quotes (') aren't. The same in single quotes returns the literal string. you would probably use single quotes, to avoid having to escape the quotes in the string and vice-versa.

What is post increment in PHP?

Post-increment. Returns $a , then increments $a by one. --$a. Pre-decrement. Decrements $a by one, then returns $a .


2 Answers

++$i is pre-increment whilst $i++ post-increment.

  • pre-increment: increment variable i first and then de-reference.
  • post-increment: de-reference and then increment i

"Take advantage of the fact that PHP allows you to post-increment ($i++) and pre-increment (++$i). The meaning is the same as long as you are not writing anything like $j = $i++, however pre-incrementing is almost 10% faster, which means that you should switch from post- to pre-incrementing when you have the opportunity, especially in tight loops and especially if you're pedantic about micro-optimisations!" - TuxRadar

For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.

like image 90
jldupont Avatar answered Oct 11 '22 08:10

jldupont


++$i increments $i, but evaluates to the value of $i+1 $i++ increments $i, but evaluates to the old value of $i.

Here's an example:

$i = 10; $a = $i++; // Now $a is 10, and $i is 11  $i = 10; $a = ++$i; // Now $a is 11, and $i is 11 

There is sometimes a slight preformance cost for using $i++. See, when you do something like

$a = $i++; 

You're really doing this:

$temporary_variable = $i; $i=$i+1; $a=$temporary_variable; 
like image 32
Shalom Craimer Avatar answered Oct 11 '22 06:10

Shalom Craimer