Assignment operators
Learn shortcut assignments with =, +=, -=, *= and /=.
Assignment operators
= is the most basic assignment operator: it puts the value on its right into the variable on its left. When you write $score = 10;, the variable $score becomes 10.
For shorter code there are compound assignment operators: +=, -=, *=, /=. $score += 5 actually means $score = $score + 5. It takes the old value, does the operation, and stores the result back in the same variable.
Why use compound assignment?
Compound assignment operators are not just shorter; they express the same meaning more clearly. When you want to add an item to a cart, writing $cart += $itemPrice is more readable than $cart = $cart + $itemPrice; the intent to add to the cart is obvious at once.
Similarly, $total -= $discount shows a discount being subtracted, and $stock *= 2 doubles the stock at a glance. Anyone reading the code understands the operation faster.
Exercise Update the cart total
Add $itemPrice to $cart using +=, then print $cart with echo. You must use the compound assignment operator.
Show example solution
To add to the cart, write $cart += $itemPrice and print it with echo.
Example solution:
<?php
$cart = 200;
$itemPrice = 50;
// Add to the cart
$cart += $itemPrice;
echo $cart;
Test yourself
-
$score = 10; $score += 5; echo $score; what is the output?
$score = 10; $score += 5; echo $score;- 5
- 10
- 15
- 50
Show answer
15 — Correct. 10 + 5 = 15.
-
Write the compound assignment operator
$score = 10; $score ____ 5; echo $score;Show answer
$score = 10; $score += 5; echo $score; -
$cart = 100; $cart -= 30; echo $cart; what is the output?
$cart = 100; $cart -= 30; echo $cart;- 70
- 130
- 100
- 30
Show answer
70 — Correct. 100 - 30 = 70.