PHP incrementing (++) and decrementing (--) operators

The PHP incrementing (++) and decrementing (--) operators are used to increment or decrement a variable value by one.

To use the operator, you add the symbol before or after the variable as shown below:

// πŸ‘‡ incrementing operator
$a = 7;
++$a; 
echo $a; // 8

// πŸ‘‡ decrementing operator
$b = 7;
--$b;
echo $b; // 6

As you can see, you only need to add the ++ or -- operator before the variable.

What’s the difference between ++var and var++ in PHP?

PHP’s incrementing and decrementing operators can be added before or after the variable name.

Adding the operator before the variable is called pre-incrementing.

Adding the operator after the variable is called post-incrementing.

The only difference between the two methods is the timing of the increment/decrement operation.

Consider the following example and notice the difference in the highlighted lines:

// πŸ‘‡ pre-increment syntax
$a = 7;
echo ++$a; // 8
echo $a; // 8

// πŸ‘‡ post-increment syntax
$a = 7;
echo $a++; // 7
echo $a; // 8

When you pre-increment a variable, the increment is done before running that increment line.

But when you post-increment a variable, the increment is done after running that increment line.

This is why the pre-increment prints the variable as 8 in the highlighted line, but post-increment prints the variable as 7.

The same logic applies to decrementing as well:

// πŸ‘‡ pre-decrement syntax
$a = 7;
echo --$a; // 6
echo $a; // 6

// πŸ‘‡ post-decrement syntax
$a = 7;
echo $a--; // 7
echo $a; // 6

In most cases, pre-incrementing is preferred over post-incrementing because it performs faster and is more intuitive.

When you increment or decrement a variable, you would expect the variable has been evaluated to the new value when the code line is running.

Finally, the increment or decrement operators only work on numbers and strings. Other types like arrays, booleans, and resources will have no effect.

And now you’ve learned how the PHP ++ and -- operators work. Nice work! πŸ˜‰

Take your skills to the next level ⚑️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.