Junior — Middle
What is the difference between increment and decrement operations in prefix and postfix forms?
sobes.tech AI
Answer from AI
In PHP, the increment (++) and decrement (--) operations can be used in prefix and postfix forms, and they differ in the order of changing the value and the returned result.
- Prefix form (++$var or --$var): first changes the variable's value, then returns the new value.
- Postfix form ($var++ or $var--): first returns the current value of the variable, then changes it.
Example:
$var = 5;
echo ++$var; // Outputs 6, variable increased before output
$var = 5;
echo $var++; // Outputs 5, variable will increase after output
This is important to consider when using in expressions to avoid unexpected results.