Incrementing operators

Author Topic: Incrementing operators  (Read 1098 times)

Offline chinmay.sahooTopic starter

  • Trade Count: (0)
  • Full Member
  • ***
  • Thank You 2
  • Posts: 158
  • Karma: 0
    • We Helpline
Incrementing operators
« on: 12-21-2015, 02:32:57 »
PHP inherits a lot of its syntax from C, and C programmers are famously proud of their own conciseness. The incrementing/decrementing operators taken from C make it possible to more concisely represent statements like $count = $count + 1, which tend to be typed frequently.

The increment operator (++) adds one to the variable it is attached to, and the decrement operator (--) subtracts one from the variable. Each one comes in two flavors, postincrement (which is placed immediately after the affected variable), and preincrement (which comes immediately before). Both flavors have the same side effect of changing the variable’s value, but they have different values as expressions. The postincrement operator acts as if it changes the variable’s value after the expression’s value is returned, whereas the preincrement operator acts as though it makes the change first and then returns the variable’s new value. You can see the difference by using the operators in assignment statements, like this:

$count = 0;
$result = $count++;
print(“Post ++: count is $count, result is $result<BR>”);
$count = 0;
$result = ++$count;
print(“Pre ++: count is $count, result is $result<BR>”);
$count = 0;
$result = $count--;
print(“Post --: count is $count, result is $result<BR>”);
$count = 0;
$result = --$count;
print(“Pre --: count is $count, result is $result<BR>”);

which gives the browser output:

Post ++: count is 1, result is 0
Pre ++: count is 1, result is 1
Post --: count is -1, result is 0
Pre --: count is -1, result is –1

In this example, the statement $result = $count++; is exactly equivalent to

$result = $count;
$count = $count + 1;

while $result = ++$count; is equivalent to

$count = $count + 1;
$result = $count;


Related Topics

  Subject / Started by Replies Last post
2 Replies
Last post 09-27-2012, 22:13:33
by rachelsjohnas