PHP Increment and Decrement Operators

Read pre-increment and post-increment correctly and keep counters clear in loops and calculations.

Lesson 29 of 86Beginner9 min read

Incrementing means increasing a value by one. Decrementing means reducing it by one. PHP offers ++ and -- for these common operations, which is why you often see $i++ in a loop. The important detail is whether the operator appears before or after the variable: both forms change the variable, but they produce different values when used inside a larger expression.

This reference teaches that difference with counters you can trace by hand. It also explains why clever combinations of several increments are difficult to maintain and why modern code should use these operators on numbers rather than imitate old string-counter tricks. If loops are new to you, work through PHP loops before adapting the examples.

Prefix and postfix answer different questions

++$count is pre-increment. PHP first increases the variable and then the expression produces the new value. $count++ is post-increment. The expression produces the old value and the variable is increased as part of the operation. After either standalone statement, the stored counter is one larger.

The same rule applies in reverse. --$count decreases the value before producing the expression result. $count-- produces the previous value and decreases the stored variable. This distinction matters when you assign the expression result to another variable or print it immediately. It does not matter for a simple standalone counter update whose result is ignored.

Think of the operator as having two effects: a changed variable and a value returned to the surrounding expression. Trace those effects separately. When a result surprises you, write down the variable before the statement, the expression result, and the variable afterward. That three-column approach is much easier than trying to memorize a collection of examples.

Use increments for counters, not hidden business rules

A loop index is a natural use because the next iteration normally moves one position forward. A completed-item count is another clear use: after successful processing, increase the count once. An inventory decrement can also be readable, but only when the surrounding transaction and validation make it clear that the change is allowed.

An increment operator does not validate a limit. If stock is zero, $stock-- produces negative stock unless your code prevents it. If a retry count is already at the permitted maximum, $attempts++ does not decide whether another attempt should happen. Keep the condition that permits the change visible next to the update.

For changes larger than one, use compound assignment such as $total += 5. Do not write five increment statements to express a five-item adjustment. Names also matter: $processedCount++ communicates more than $x++. In business logic, the variable's meaning and the moment of update are usually more important than choosing the shortest operator.

Avoid depending on complex expression evaluation

Do not write expressions that both read and modify the same counter several times, such as combining $i++ and ++$i in one arithmetic statement. PHP's general evaluation order is not a promise you should build business rules around. Even when a particular run produces a result you can explain, a reader must spend effort reconstructing side effects.

Split the work into statements with meaningful names. Store the old value, update the counter, and then calculate the result. This also makes debugging easier because you can inspect the intermediate state without altering the expression. A few extra lines often remove a whole class of mistakes.

Incrementing an integer near its maximum can promote the result to a float. A float may not distinguish adjacent integers at large magnitudes. Therefore, ++ is unsuitable for generating guaranteed unique database identifiers or an unlimited sequence. Let the database assign identities, or use an identifier system designed for your required range and concurrency.

PHP Increment and Decrement Operators Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Trace post-increment and pre-increment

The first assignment stores four in $old, then leaves $count at five. The next operation increases the counter to six and stores that new value in $new. The output deliberately prints both the expression result and stored counter, so you can observe the difference directly.

PHP
<?php
$count = 4;
$old = $count++;
echo $old . ':' . $count . PHP_EOL;
$new = ++$count;
echo $new . ':' . $count . PHP_EOL;
Output
4:5
6:6
Example 2

Count only successful records

The counter changes only inside the successful branch. Its expression result is discarded, so postfix is a style choice here rather than a source of different behavior. If you move the increment outside the condition, the program counts all records instead. That is a logic change, even though the operator remains the same.

PHP
<?php
$records = [true, false, true, true];
$processedCount = 0;
foreach ($records as $successful) {
    if ($successful) {
        $processedCount++;
    }
}
echo $processedCount . PHP_EOL;
Output
3

Common PHP Increment and Decrement Operators Mistakes

Applying numeric counter habits to strings and booleans

Older PHP examples show letters increasing from one string to another. PHP has historical string increment behavior, but relying on it for numeric counters is confusing and subject to version-specific diagnostics. PHP 8.3 introduced changes around unsupported increment/decrement types and added dedicated string increment/decrement functions. Booleans and null also have behaviors that should not be used to disguise a counter's type.

Initialize counters as integers, validate external values before using them, and choose explicit string operations when the domain is text. Review the PHP increment and decrement manual when maintaining legacy behavior. If input arrives as a string, do not let an increment become an accidental conversion policy. Parse the intended integer first and reject invalid values.

PHP Increment and Decrement Operators in Real Projects

Practical task: number only visible items

You have three product names, but one is an internal placeholder. Print consecutive public row numbers for the remaining names. Start at zero and pre-increment only after deciding that an item will be displayed. The expected output should contain rows one and two, with no gap caused by the skipped placeholder.

PHP
<?php
$names = ['Notebook', '_placeholder', 'Pencil'];
$rowNumber = 0;
foreach ($names as $name) {
    if ($name === '_placeholder') {
        continue;
    }
    $displayNumber = ++$rowNumber;
    echo $displayNumber . '. ' . $name . PHP_EOL;
}
Output
1. Notebook
2. Pencil

The continue statement skips the increment and output for the placeholder. Pre-increment gives the display line the new row number immediately. An equally clear alternative is a standalone $rowNumber++ followed by output. Try moving the update above the condition and explain why Pencil then appears as row three. The location of the update defines what you count.

PHP Increment and Decrement Operators FAQ

Is ++$i always better than $i++?

No. Choose the form that expresses whether you need the new or old value. For standalone updates with ignored results, readability and project style guide the choice.

Can I increment a number literal?

No. The operation needs a writable value such as a variable. Writing 5++ does not provide storage that PHP can update.

Does -- stop at zero?

No. A counter can become negative. Add a condition when zero is a business boundary, and handle concurrent stock changes at the database level when relevant.

Should the loop counter also be a display number?

Only when they count the same thing. If rows are skipped or filtered, keep a separate display counter as the practical task demonstrates.

Can I use increment as input validation?

No. A successful arithmetic operation does not prove that the original value satisfied the required format or range.

PHP Increment and Decrement Operators Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

A count must increase by seven after a batch. Which statement states that clearly?

PHP Increment and Decrement Operators Quiz

2 questions to check what you learned.

  1. Starting with $n = 2, what value is assigned by $old = $n++?

    • 3
    • 2
    • 1
  2. Which statement decreases $n and produces its new value?

    • $n--
    • $n -= 0
    • --$n