Increment and Decrement Operators - PHP - P18

Опубликовано: 30 Октябрь 2024
на канале: Dino Cajic
185
4

PHP contains increment and decrement operators. These are operators that either add 1 or subtract 1 from the current value. The operators can be prefixed or post-fixed and will yield slightly different results each time.

Increment Operator: ++
Decrement Operator: --

Normally, to add 1 to a value, you would use the addition operator.

$a = 5;
$a = $a + 1;
var_dump($a);

In the example above, you evaluate the expression on the right, $a + 1, which becomes 6, and then you assign the value back to $a, on the left.

With the postfix-increment operator, we can append ++ to the end of the variable and it will do the same operation. 

$b = 5;
var_dump($b++); // still displays 5
var_dump($b); // displays 6

But if we evaluate the variable, we get an unexpected result: 5. If we were adding 1 to the value, why does it still display 5 and not 6? With the postfix-increment operator, the value is displayed first, and then the operation is performed. If we call the value after, it will display the previous value plus 1.
With the prefix-increment operator, the expression is evaluated first, and is then displayed.

$c = 5;
var_dump(++$c); // displays 6
var_dump($c); // still displays 6

You only have to keep this in mind if you're performing the operation inside of an expressions or passing the variable as an argument. If you increment the value and then call it, the result will be the same regardless of whether you prefix or post-fix the operator.

$a = 5;
$a++;
echo $a; // prints 6

$b = 5;
++$b;
echo $b; // prints 6

$c = 5;
echo $c++; // prints 5
echo $c; // prints 6

$d = 5;
echo ++$d; // prints 6

The same principle applies to the decrement operator, but instead of adding 1 to the value, you subtract 1.

$a = 5;
$a--;
echo $a; // prints 4

$b = 5;
--$b;
echo $b; // prints 4

$c = 5;
echo $c--; prints 5
echo $c; prints 4

$d = 5;
echo --$d; // prints 4

Increment and decrement operators are used heavily in loops.

Read the full article on my website
https://www.dinocajic.com/php-increme...

Code for this tutorial
https://github.com/dinocajic/php-7-yo...

Full Code
https://github.com/dinocajic/php-7-yo...

PHP Playlist
   • PHP Tutorial  

--
Dino Cajic
Author and Head of IT

Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium:   / dinocajic  
Instagram:   / think.dino  
LinkedIn:   / dinocajic  
Twitter:   / dino_cajic  

My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268

Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw

Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN