Combined Assignment
Part of the Fundamentals section of Coddy's PHP journey — lesson 18 of 71.
When you need to update a variable based on its current value, PHP offers a shorthand called combined assignment operators. Instead of writing the variable name twice, you can combine the operation with the assignment.
For example, to add 10 to a variable:
<?php
$score = 50;
$score = $score + 10; // The long way
$score += 10; // The shorthand way
?>Both lines do the same thing, but += is shorter and cleaner. This pattern works with all arithmetic operators:
| Operator | Example | Equivalent To |
+= | $x += 5 | $x = $x + 5 |
-= | $x -= 3 | $x = $x - 3 |
*= | $x *= 2 | $x = $x * 2 |
/= | $x /= 4 | $x = $x / 4 |
%= | $x %= 3 | $x = $x % 3 |
**= | $x **= 2 | $x = $x ** 2 |
<?php
$balance = 100;
$balance -= 25; // $balance is now 75
$balance *= 2; // $balance is now 150
echo $balance; // Outputs: 150
?>Challenge
EasyRead two numbers from input: a starting value and an adjustment amount.
Store the starting value in a variable called $total. Then perform the following operations using combined assignment operators:
- Add the adjustment amount to
$total - Multiply
$totalby 3 - Subtract 10 from
$total
Print the final value of $total.
Example:
If the inputs are 20 and 5, the output should be 65 because:
- Start with 20, add 5 → 25
- Multiply by 3 → 75
- Subtract 10 → 65
Cheat sheet
PHP provides combined assignment operators as shorthand for updating a variable based on its current value:
| Operator | Example | Equivalent To |
+= | $x += 5 | $x = $x + 5 |
-= | $x -= 3 | $x = $x - 3 |
*= | $x *= 2 | $x = $x * 2 |
/= | $x /= 4 | $x = $x / 4 |
%= | $x %= 3 | $x = $x % 3 |
**= | $x **= 2 | $x = $x ** 2 |
<?php
$score = 50;
$score += 10; // Add 10 to $score
$score -= 5; // Subtract 5 from $score
$score *= 2; // Multiply $score by 2
?>Try it yourself
<?php
// Read input
$startingValue = intval(fgets(STDIN));
$adjustmentAmount = intval(fgets(STDIN));
// Store the starting value in $total
$total = $startingValue;
// TODO: Write your code below
// Use combined assignment operators to:
// 1. Add the adjustment amount to $total
// 2. Multiply $total by 3
// 3. Subtract 10 from $total
// Output the result
echo $total;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators