Unary Increment & Decrement Operators

Posted by tutor | Posted in PHP Tutorial | Posted on 03-08-2010-05-2008

0

Normally we use binary operators for arithmetic operations. Binary operators are the operators which require two variables to act upon.

But the increment job can also be done by unary operators. Unary operators are the operators which act upon a single variable.

PHP provides four unary operators for performing increment and decrement operations.

The first operator is pre-increment ie ++

    $x++; is equivalent to $x += 1; or $x = $x + 1;

Similarly there is pre-decrement operator denoted by –

    $x–; Which is equivalent to $x -= 1; or $x = $x – 1;

In the above two cases, what happens at the background is, first the value of the variable “x” is assigned to any variable, if an assignment operator is present, then the value of the variable is incremented or decremented.

The third operator is post-increment. It is also denoted by ++, but the placing changes

    ie ++$x; is equivalent to $x += 1; or $x = $x + 1;

The last one is post-decrement, ie –

    –$x; Which is equivalent to $x -= 1; or $x = $x – 1;

In this case the value of the variable is first incremented or decremented then the value is assigned

    For eg:

    $x = 4;
    echo “The value of x++ is ” . $x++;
    echo “<br />Now the value of x is” . $x;
    $x = 4;
    echo “<br />The value of ++x is ” . ++$x;
    echo “<br />Now the value of x is ” . $x;
    }

    Output:

    The value of x++ is 4
    Now the value of x is 5
    The value of ++x is 5
    Now the value of x is 5

As you can see that the incremented value of $x++ is not reflected in the echoed text because the variable is not incremented until after the line of code is executed. However, with the pre-increment “++$x” the variable does reflect the addition immediately.

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.