PHP Assignment Operators Explained with Examples

What Are PHP Assignment Operators?

In PHP, assignment operators are used to assign values to variables.
The most basic one is the equal sign (=), which assigns the value on the right-hand side (RHS) to the variable on the left-hand side (LHS).

However, PHP also provides compound assignment operators, which combine arithmetic or string operations with assignment — making your code shorter and faster.

Let’s understand them step-by-step with examples.

Basic Assignment Operator (=)

The equal sign (=) assigns the value of the right-hand side to the variable on the left-hand side.

Example:

<?php
$x = 10;
echo $x;
?>

Output:

 
10

Explanation:
The value 10 is stored in variable $x.

Add and Assign Operator (+=)

Adds the right-hand value to the left-hand variable and stores the result in the same variable.

Example:

<?php
$x = 10;
$x += 5; // Same as $x = $x + 5
echo $x;
?>

Output:

 
15

Subtract and Assign Operator (-=)

Subtracts the right-hand value from the left-hand variable and stores the result.

Example:

<?php
$x = 20;
$x -= 8; // Same as $x = $x - 8
echo $x;
?>

Output:

 
12

Multiply and Assign Operator (*=)

Multiplies the variable by the value on the right and stores the result.

Example:

<?php
$x = 6;
$x *= 3; // Same as $x = $x * 3
echo $x;
?>

Output:

 
18

Divide and Assign Operator (/=)

Divides the variable by the right-hand value and stores the result.

Example:

<?php
$x = 100;
$x /= 5; // Same as $x = $x / 5
echo $x;
?>

Output:

 
20

Modulus and Assign Operator (%=)

Divides the variable by the right-hand value and stores the remainder.

Example:

<?php
$x = 13;
$x %= 5; // Same as $x = $x % 5
echo $x;
?>

Output:

 
3

Concatenation and Assign Operator (.=)

Used to append (join) a string to an existing string variable.

Example:

<?php
$text = "Hello";
$text .= " World!";
echo $text;
?>

Output:

 
Hello World!

Explanation:
$text .= " World!" is the same as $text = $text . " World!".

Real-World Use Example

Let’s apply assignment operators in a practical program.

Example: Calculate Salary Bonus

<?php
$salary = 50000;
$bonus = 5000;

// Add bonus to salary
$salary += $bonus;

echo "Total Salary: ₹$salary";
?>

Output:

 
Total Salary: ₹55000

Explanation:
$salary += $bonus adds the bonus to the base salary and updates the total.

Common Mistakes to Avoid

  • Writing $x =+ 5; instead of $x += 5;
  • The first means $x = +5, not addition assignment.
  • Using .= with numbers (works only with strings).
  • Always check data type before using arithmetic or concatenation operators.