PHP Assignment Operators

Assignment operators are used to assign values to variables in PHP. But did you know they can do more than just =? Let’s explore them in a fun way!

📌 What Are Assignment Operators?

They are used to **assign values to variables** and can also perform calculations at the same time.

Operator Description Example
= Assign a value $x = 10;
+= Add and assign $x += 5; // $x = $x + 5
-= Subtract and assign $x -= 3; // $x = $x - 3
*= Multiply and assign $x *= 2; // $x = $x * 2
/= Divide and assign $x /= 4; // $x = $x / 4
%= Modulus and assign $x %= 2; // $x = $x % 2

✅ Assigning Values with =

The simplest operator! Just store a value in a variable.

<?php
    $x = 10;
    echo "Value of x: " . $x;
?>
    

Try It Now

➕ Addition Assignment +=

Adds a value to a variable and stores the result.

<?php
    $x = 5;
    $x += 3; // Same as $x = $x + 3
    echo "Updated value of x: " . $x;
?>
    

Try It Now

➖ Subtraction Assignment -=

Subtracts a value from a variable.

<?php
    $x = 10;
    $x -= 4; // Same as $x = $x - 4
    echo "Updated value of x: " . $x;
?>
    

Try It Now

✖ Multiplication Assignment *=

Multiplies and assigns the result.

<?php
    $x = 7;
    $x *= 2; // Same as $x = $x * 2
    echo "Updated value of x: " . $x;
?>
    

Try It Now

➗ Division Assignment /=

Divides and assigns the result.

<?php
    $x = 20;
    $x /= 5; // Same as $x = $x / 5
    echo "Updated value of x: " . $x;
?>
    

Try It Now

🎯 Recap – Key Takeaways

  • = assigns a value.
  • += adds and assigns.
  • -= subtracts and assigns.
  • *= multiplies and assigns.
  • /= divides and assigns.
  • %= calculates modulus and assigns.

📝 Practice & Experiment!

Modify the examples above and play around with different values. The best way to learn is by doing!