Menu
Coddy logo textTech

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:

OperatorExampleEquivalent 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 icon

Challenge

Easy

Read 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:

  1. Add the adjustment amount to $total
  2. Multiply $total by 3
  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:

OperatorExampleEquivalent 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;
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals