Home > Backend Development > PHP Tutorial > What's the Difference Between Pre- and Post-Increment/Decrement Operators in PHP?

What's the Difference Between Pre- and Post-Increment/Decrement Operators in PHP?

DDD
Release: 2025-01-02 12:37:39
Original
386 people have browsed it

What's the Difference Between Pre- and Post-Increment/Decrement Operators in PHP?

Reference Guide: What does this symbol mean in PHP? (PHP Syntax)

In PHP, the and -- operators are used for incrementing or decrementing variables.

Increment Operator ( )

  • Pre-increment ( $variable): Increments the variable by one and then returns the incremented value.
  • Post-increment (variable ): Returns the current value of the variable, then increments it by one.

Decrement Operator (--)

  • Pre-decrement (--variable): Decrements the variable by one and then returns the decremented value.
  • Post-decrement (variable--): Returns the current value of the variable, then decrements it by one.

Usage

These operators can be used before or after the variable to achieve different results:

  • Pre-increment/decrement: The variable is modified before it is used.
  • Post-increment/decrement: The variable is used and then modified.

Example

Consider the following code:

$count = 10;
echo "Before: $count\n";
echo "Pre-increment: " . ++$count . "\n";
echo "Post-increment: " . $count++ . "\n";
echo "Pre-decrement: " . --$count . "\n";
echo "Post-decrement: " . $count-- . "\n";
Copy after login

Output

Before: 10
Pre-increment: 11
Post-increment: 11
Pre-decrement: 10
Post-decrement: 10
Copy after login

This demonstrates how the increment/decrement operators can be used in different scenarios. Notice that in the post-increment and post-decrement cases, the original value of the variable is used first before being modified.

The above is the detailed content of What's the Difference Between Pre- and Post-Increment/Decrement Operators in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template