PHP

📝 Assignment Operators in PHP

Assignment Operators in PHP are used to set, update, or modify values stored in variables. The basic assignment operator is =, but PHP also supports compound assignment operators that perform a mathematical or string operation and assign the result in a single step.

  • Compound Assignment: Combining an operation with assignment (e.g., $a += $b) is shorthand for $a = $a + $b. It makes your code cleaner and more readable.

🛠️ Basic and Compound Assignment Operators

1️⃣ Basic Assignment Operator (=)
Sets the right-hand expression value to the variable on the left.

PHP
$a = 8; // $a is now 8

// Chained / Multiple assignment
$a = $b = 8; // Both $a and $b become 8

2️⃣ Concatenation Assignment (.=)
Appends the right-side string onto the end of the left-side variable string.

PHP
$a = "Hello ";
$b = "World";

$a .= $b; // Same as: $a = $a . $b
echo $a;  // Outputs: Hello World

3️⃣ Arithmetic Compound Assignments (+=, -=, *=, /=, %=)
Performs mathematical operations directly on the targeted variable:

PHP
// Addition Assignment (+=)
$a = 5;
$a += 3; // $a is now 8

// Subtraction Assignment (-=)
$a = 10;
$a -= 4; // $a is now 6

// Multiplication Assignment (*=)
$a = 5;
$a *= 2; // $a is now 10

// Division Assignment (/=)
$a = 20;
$a /= 4; // $a is now 5

// Modulus Assignment (%=)
$a = 10;
$a %= 3; // $a is now 1 (Remainder of 10 / 3)

💡 Real-World Practical Example

Updating balances, shopping cart totals, or accumulated values:

PHP
$money = 100;
$expense = 30;

$money -= $expense; // Remaining balance: 70
echo "Remaining balance: " . $money . " TL";

📊 Assignment Operators Reference Table

Operator Example Equivalent To Operation
= $a = $b $a = $b Assign
+= $a += $b $a = $a + $b Add and assign
-= $a -= $b $a = $a - $b Subtract and assign
*= $a *= $b $a = $a * $b Multiply and assign
/= $a /= $b $a = $a / $b Divide and assign
%= $a %= $b $a = $a % $b Modulus and assign
.= $a .= $b $a = $a . $b Concatenate and assign
  • 📝 Short Summary

  • Assignment operators assign or update values inside variables.
  • Compound assignment shortcuts reduce code redundancy and improve execution clarity.
  • The .= operator is widely used in PHP to construct HTML markup or multi-line string templates dynamically.