PHP Basics
Functions in PHP
Working with Forms
Working with Files
Working with Databases
Advanced PHP Techniques

In PHP, increment (++) and decrement (–) operators are used to increase or decrease the value of a variable by one. These operators can be used in two different forms: prefix and postfix. Understanding the difference between these forms is crucial as they affect the value of the variable in different ways. Let’s look at each in detail.

Increment Operator (++)

The increment operator increases the value of a variable by one.

Prefix Increment (++$variable)

In prefix increment, the value of the variable is incremented before it is used in an expression.

				
					$variable = 5;
echo ++$variable;  // Outputs: 6
echo $variable;    // Outputs: 6

				
			

Here, ‘$variable‘ is incremented before its value is output, so the output is 6.

Postfix Increment ($variable++)

In postfix increment, the value of the variable is used in an expression before it is incremented.

				
					$variable = 5;
echo $variable++;  // Outputs: 5
echo $variable;    // Outputs: 6

				
			

In this example, the original value of ‘$variable‘ (which is 5) is output first, and then ‘$variable‘ is incremented by 1. So, the second output shows the incremented value 6.

Decrement Operator (--)

The decrement operator decreases the value of a variable by one.

Prefix Decrement (--$variable)

In prefix decrement, the value of the variable is decremented before it is used in an expression.

				
					$variable = 5;
echo --$variable;  // Outputs: 4
echo $variable;    // Outputs: 4

				
			

Here, ‘$variable‘ is decremented before its value is output, so the output is 4.

Postfix Decrement ($variable--)

In postfix decrement, the value of the variable is used in an expression before it is decremented.

				
					$variable = 5;
echo $variable--;  // Outputs: 5
echo $variable;    // Outputs: 4

				
			

In this example, the original value of ‘$variable‘ (which is 5) is output first, and then ‘$variable‘ is decremented by 1. So, the second output shows the decremented value 4.

  • Prefix Increment (++$variable): Increments the variable and then returns the value.
  • Postfix Increment ($variable++): Returns the value of the variable, then increments it.
  • Prefix Decrement (–$variable): Decrements the variable and then returns the value.
  • Postfix Decrement ($variable–): Returns the value of the variable, then decrements it.

These operators are handy for loop counters, updating numeric values, and performing arithmetic operations concisely in PHP.

Scroll to Top