PHP: Increment & Decrement

Post

Posted
Rating:
#11 (In Topic #11)
Avatar
Christian
Keystone is in the usergroup ‘Moderator’

A quick overview of how it works.

POST-INCREMENT ($a++):

Keep in mind with this operator that what comes first gets processed first. (ie: $a++ or ++$a)

For $a++ the rule tells us that we must solve the variables first and then apply the ++ (1+) operator. As a result, the operator does not depend on the variable solving process

  • So if: $a=2 $b=$a++

  • That means: $a=2 $b=$a ---> $b=2

Then solve the ++ (+1) operation

  • $a=2, $a++ = 2+1 ($a+1) ---> $a++=3, $a=3

Answer Post-increase:

  • ($a++): $a=3 $b=2

 

PRE-INCREMENT (++$a):

The rule says that the ++ (1+) operator gets processed first and then the rest of the variables.

  • So: $a=2 $b=++$a

  • That means: $a=2(+1) --> $a=3

After the ++ operation the variables may be solved.

  • So: $a=3, $b=a --> $b=3

Because the ++ operator was already solved at the beginning, it does not need to be solved again.

  • Answer of Pre-increase: (++$a): $a=3 $b=3

 

Decrement works in the same fashion.

Last edit: by Mehtuus

Online now: No Back to the top
1 guest and 0 members have just viewed this.