Shorthand Operators - PHP - P22

Опубликовано: 01 Октябрь 2024
на канале: Dino Cajic
221
7

Shorthand operators are amazing! There, I said it. The shorthand operator combines the expression on the right with the assignment operator. The variable that appears on the left-side of the assignment operator needs to appear on the right-hand-side as well in order for you to be able to use the shorthand notation.

Let's take a look at the following code:

$x = 1;
$x = $x + 1;
echo $x;

1. PHP assigns the integer value 1 to the variable $x.
2. In the second statement, $x + 1 is evaluated. $x contains the value 1, so the result will be 1 + 1, which equals 2.
3. The value 2 is then assigned to $x.

If you echo out $x, 2 will be displayed.

Since the variable $x appears on both sides of the assignment operator, we can use the shorthand operator to shorten the expression $x = $x + 1. You just remove the $x from the right hand side and move the + operator in front of the = operator: $x += 1.

// Long approach
$x = $x + 1;

// Can be shortened to
$x += 1;

Shorthand operations are not limited to integers; you can use the concatenation shorthand operator to combine strings.

// Before
$msg = "Hey";
$msg = $msg . " there";

// After
$msg = "Hey";
$msg .= " there";

We can apply the same logic to the subtraction, multiplication and even the modulus operators.

$x = 0;
// Same as $x = $x + 4;
// $x = 0 + 4;
// $x = 4
$x += 4;

// Same as $x = $x - 2;
// $x = 4 - 2;
// $x = 2;
$x -= 2;

// Same as $x = $x * 2;
// $x = 2 * 2;
// $x = 4;
$x *= 2;

// Same as $x = $x % 2;
// $x = 4 % 2;
// $x = 0;
$x %= 2;

Shorthand operators are used frequently throughout programming; they're so frequent that it's actually rare that you'll see the long approach in the wild. There are operations that are so frequently used that even shorter operators have been created. I'm talking about the increment and decrement operators, which we covered recently.

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

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