Web Analytics

PHP Increment & Decrement Operators

Beginner~15 min read

Increment (++) and decrement (--) operators provide shortcuts for adding or subtracting 1. Understanding the difference between pre and post operations is crucial!

Operators Overview

Operator Name Effect
++$x Pre-increment Increment first, then return
$x++ Post-increment Return first, then increment
--$x Pre-decrement Decrement first, then return
$x-- Post-decrement Return first, then decrement
Output
Click Run to execute your code

Pre vs Post Increment

<?php
// Pre-increment: increment FIRST, then use
$x = 5;
echo ++$x;  // Outputs: 6 (incremented to 6, then returned)
echo $x;    // Outputs: 6

// Post-increment: use FIRST, then increment
$x = 5;
echo $x++;  // Outputs: 5 (returned 5, then incremented)
echo $x;    // Outputs: 6
?>

Common Use: Loops

<?php
// Most common use in for loops
for ($i = 0; $i < 5; $i++) {
    echo $i . " ";  // 0 1 2 3 4
}

// Counting down
for ($i = 5; $i > 0; $i--) {
    echo $i . " ";  // 5 4 3 2 1
}
?>

Summary

  • ++$x: Pre-increment (increment first)
  • $x++: Post-increment (return first)
  • --$x: Pre-decrement (decrement first)
  • $x--: Post-decrement (return first)
  • Common use: Loop counters

What's Next?

Next, we'll explore the Ternary and Null Coalescing Operators - powerful shortcuts for conditional assignments!