PHP Assignment Operators Explained with Examples
Assignment operators in PHP are used to assign values to variables. They are among the most commonly used operators and are essential for writing any PHP program.
In this beginner-friendly guide, you’ll learn all PHP assignment operators with examples, explanations, and best practices.
What Are Assignment Operators in PHP?
Assignment operators are used to set or update the value of a variable.
Basic idea:
Take a value → Assign it to a variable
Basic Assignment Operator (=)
<?php
$x = 10;
echo $x;
?>
Explanation
$xis assigned the value10- Output will be: 10
List of PHP Assignment Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| = | Assignment | $x = 5 | Assign 5 |
| += | Add and assign | $x += 3 | $x = $x + 3 |
| -= | Subtract and assign | $x -= 2 | $x = $x – 2 |
| *= | Multiply and assign | $x *= 4 | $x = $x * 4 |
| /= | Divide and assign | $x /= 2 | $x = $x / 2 |
| %= | Modulus and assign | $x %= 3 | Remainder |
| .= | Concatenate and assign | $str .= “Hi” | Append string |
Add and Assign (+=)
<?php
$x = 5;
$x += 3;
echo $x;
?>Explanation
$x += 3means$x = $x + 3- Output: 8
Subtract and Assign (-=)
<?php
$x = 10;
$x -= 4;
echo $x;
?>Explanation
$x -= 4means$x = $x - 4- Output: 6
Multiply and Assign (*=)
<?php
$x = 3;
$x *= 5;
echo $x;
?>Explanation
$x *= 5means$x = $x * 5- Output: 15
Divide and Assign (/=)
<?php
$x = 20;
$x /= 4;
echo $x;
?>Explanation
$x /= 4means$x = $x / 4- Output: 5
Modulus and Assign (%=)
<?php
$x = 10;
$x %= 3;
echo $x;
?>Explanation
$x %= 3means remainder of 10 ÷ 3- Output: 1
Concatenate and Assign (.=)
Used to append (join) a string to an existing string variable.
<?php
$str = "Hello";
$str .= " World";
echo $str;
?>Explanation
- Appends text to existing string
- Output: Hello World
Real-World Use Cases
Shopping Cart Total
$total = 100;
$total += 50; // add itemCounter Increment
$count = 0;
$count += 1;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.
FAQs
What are assignment operators in PHP?
They are used to assign or update values in variables.
What is the difference between = and +=?
=assigns value+=adds and assigns
Can assignment operators be used with strings?
Yes, using .= operator.
Why use shorthand operators?
They make code shorter and cleaner.
Are assignment operators important?
Yes, they are used in almost every PHP program.