Jump to content

Prefix decrementing operator VS. Postfix decrementing Operator


seangz

Recommended Posts

I'm having trouble understanding the behavior of Prefix decrementing operator VS. Postfix decrementing Operator

 

Postfix decrementing Operator

<?php

$a = 1;

$a = --$a + 1;

echo $a;

// this outputs 1

?>

 

 

VS....

 

Prefix decrementing operator

<?php

$a = 1;

$a = $a-- + 1;

echo $a;

// this outputs 2

?>

 

 

 

First, your examples are backwards.

 

$a++ / $a-- is a postfix increment (or decrement).  The ++ or -- comes after (post) the variable.

++$a / --$a is a prefix increment (or decrement).  The ++ or -- comes before (pre) the variable.

 

 

Prefix increment causes the variables value to be incremented and then returned.  eg:

$a=10;
$b = ++$a;

//is the same as
$a = 10;
$a = $a + 1;
$b = $a;

 

Postfix increment causes the varaibles value to be returned, then incremented after.

$a = 10;
$b = $a++;

//is the same as
$a = 10;
$b = $a;
$a = $a + 1;

 

Decrement is the exact same, but subtracting one rather than adding one.

 

I guess I can understand that, but I'm still trying to wrap my head around the postfix behavior.

for example

 

<?php


$a = 2;

$a--;


echo $a;

// this outputs 1

$a = $a--;

//this, for some reason, doesn't do anything...????

echo '<br />' . $a;

?>

i.e. isn't

$a = $a--;

the same thing as

$a--;

 

No.  -- and ++ work on the variable directly.  Using the variable that you apply the ++/-- to elsewhere in the same statement generally falls under the category 'Undefined Behavior'.  This means the computer can do whatever it wants and it'll be considered a valid response to the operation.  I'm not sure if php defines this behavior or not.  I know for instance C does not.

 

 

The statement $a = $a--; could be interpreted as multiple different actions sequences, which each would have separate outputs.  Assume $a=10 to start with, it could be:

$a=10;
$tmp = $a; //save the value of $a for use later.
$a = $a - 1; // the -- operation
$a = $tmp; //use the previous value of $a
//final result is $a = 10.  The -- is essentially nullified.

 

or it could be run as:

$a = 10;
$a = $a; //Use the current $a;
$a = $a - 1; //run the -- operation
//final result is $a=9.

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.