HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Increment / Decrement Operators

Increment and decrement operators are used to increase or decrease a variable's value by one. They are widely used in loops (like for and while) and for simple counter updates.


Table of Operators

The following table lists the four variations of these operators:

Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

Pre vs. Post: What's the Difference?

The position of the ++ or -- symbols determines when the value is updated relative to when it is used in the rest of the expression.

1. Pre-increment (++$x)

Think of it as "Update then Use." PHP first adds one to the variable, and the new value is used immediately.

<?php
    $x = 10;  
    echo ++$x; // Outputs: 11
    // $x is now 11
?>

2. Post-increment ($x++)

Think of it as "Use then Update." PHP first uses the current value of the variable, and only *after* that statement is finished does it add one.

<?php
    $x = 10;  
    echo $x++; // Outputs: 10
    // BUT internally, $x is now 11!
    echo $x;   // Outputs: 11
?>

String Incrementing

Interestingly, PHP also allows the increment operator (++) to work on strings. It follows the "carry" logic used in Excel columns (A → B, Z → AA).

<?php
    $s = "a";
    echo ++$s; // Outputs: b

    $z = "z";
    echo ++$z; // Outputs: aa
?>
Note: Decrement operators (--) do not work on strings in PHP. They only work on numerical values.
Common Use Case: You will mostly see $i++ inside the update part of a for loop to keep track of iterations.

Key Points to Remember

  • Increment/Decrement is always by a value of exactly one.
  • Pre-operators update the variable before returning it.
  • Post-operators update the variable after returning it.
  • The $x++ style is the most common in web development loops.
  • These operators only work on variables, not literal values (like 5++).