Menu
Coddy logo textTech

Increment/Decrement

Part of the Fundamentals section of Coddy's PHP journey — lesson 19 of 71.

When you need to add or subtract exactly 1 from a variable, PHP provides an even shorter way than combined assignment: the increment and decrement operators.

The increment operator (++) adds 1 to a variable, while the decrement operator (--) subtracts 1:

<?php
$count = 5;
$count++;  // $count is now 6
$count--;  // $count is now 5 again
?>

These operators can be placed before or after the variable, which affects when the change happens:

<?php
$a = 5;
echo $a++;  // Outputs: 5, then $a becomes 6
echo $a;    // Outputs: 6

$b = 5;
echo ++$b;  // $b becomes 6, then outputs: 6
?>

With $a++ (post-increment), the original value is used first, then incremented. With ++$b (pre-increment), the value is incremented first, then used. The same logic applies to -- for decrementing.

challenge icon

Challenge

Easy

Read a number from input and store it in a variable called $counter.

Perform the following operations in order, printing the result of each echo statement on a new line:

  1. Print the value of $counter++ (post-increment)
  2. Print the current value of $counter
  3. Print the value of ++$counter (pre-increment)
  4. Decrement $counter using -- (no print needed)
  5. Print the final value of $counter

Example:

If the input is 10, the output should be:

10
11
12
11

Explanation:

  • Post-increment prints 10, then $counter becomes 11
  • Current value is 11
  • Pre-increment makes $counter 12, then prints 12
  • Decrement makes $counter 11
  • Final value is 11

Cheat sheet

The increment operator (++) adds 1 to a variable, while the decrement operator (--) subtracts 1:

<?php
$count = 5;
$count++;  // $count is now 6
$count--;  // $count is now 5 again
?>

These operators can be placed before or after the variable:

  • Post-increment ($a++): uses the original value first, then increments
  • Pre-increment (++$a): increments first, then uses the new value
<?php
$a = 5;
echo $a++;  // Outputs: 5, then $a becomes 6
echo $a;    // Outputs: 6

$b = 5;
echo ++$b;  // $b becomes 6, then outputs: 6
?>

The same logic applies to the decrement operator (--).

Try it yourself

<?php
// Read input
$counter = intval(fgets(STDIN));

// TODO: Write your code below
// 1. Print the value of $counter++ (post-increment)

// 2. Print the current value of $counter

// 3. Print the value of ++$counter (pre-increment)

// 4. Decrement $counter using -- (no print needed)

// 5. Print the final value of $counter

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals