CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

PHP Assignment Operators

Assignment operators are used with numeric values to write a value to a variable. The most basic assignment operator is the equal sign (=), which sets the value of the left operand to the value of the expression on the right.


The Basic Assignment (=)

In PHP, the = does not mean "equals" (that is handled by comparison operators). Instead, it means **"set the value of."**

<?php
    $x = 10; // $x now holds the value 10
?>

Table of Assignment Operators

PHP also provides "shorthand" operators that combine a mathematical operation with assignment.

Operator Same as... Description
x = y x = y Assigns value of y to x
x += y x = x + y Addition and assignment
x -= y x = x - y Subtraction and assignment
x *= y x = x * y Multiplication and assignment
x /= y x = x / y Division and assignment
x %= y x = x % y Modulus and assignment

Practical Example

Using shorthand operators makes your code cleaner and easier to read, especially when updating totals in a loop.

<?php
    $total = 100;
    $tax = 15;

    $total += $tax; // Instead of $total = $total + $tax;
    echo $total; // Outputs: 115
?>
Important Distinction: Remember that $x = $y is an **assignment**, while $x == $y is a **comparison**. Distinguishing these two is vital for logic!
String Assignment: You can also use .= to append a string to an existing variable. (e.g., $name .= " Doe";).

Key Points to Remember

  • The = operator sets a value; it doesn't compare them.
  • Shorthand operators (like +=) combine math and assignment.
  • Using shorthand makes code cleaner and more professional.
  • Shorthand math works the same way for subtraction, multiplication, and division.
  • Always remember that the variable being updated must be on the left side.