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

Viewed 91101

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

15 Answers

$i++ is known as post-increment. It increments the value of $i only after assigning the original value of $i to $j first.

++$i is known as pre-increment. It increments the value of $i before assigning the value to $j, so the updated value of $i will be assigned to $j.

Hence,

$i = 4;
$j = $i++;
// Now, $i = 5 and $j = 4

$i = 4;
$j = ++$i;
// Now, $i = 5 and $j = 5

These theories apply in a similar manner for decrementing as well.

Hope this helps!

Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.

1. The prefix increment returns the value of a variable after it has been incremented.

2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.

// Prefix increment

let prefix = 1;
console.log(++prefix); // 2

console.log(prefix); // 2

// Postfix increment

let postfix = 1;

console.log(postfix++); // 1

console.log(postfix); // 2

To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

Related