Assignment Operators
What Is an Assignment Operator? In simple terms: An assignment operator stores a value in a variable. The basic one is = , which means "put the value on the right into the variable on the left". Techn
What Is an Assignment Operator?
In simple terms: An assignment operator stores a value in a variable. The basic one is =, which means "put the value on the right into the variable on the left".
Technically: The assignment operator evaluates the expression on its right side and binds the result to the variable (or array element, or property) on its left side. The whole assignment is itself an expression whose value is the assigned value. Compound assignment operators such as += combine an operation and an assignment in one step.
Why They Matter
Programs constantly create and update state: running totals, counters, accumulated text, default settings, flags. Assignment operators express these updates concisely and clearly.
Basic Assignment: =
Syntax
$variable = expression;
Example
<?php
$name = "Kavin";
$score = 72 + 8;
$passed = $score >= 40;
var_dump($name, $score, $passed);
Output
string(5) "Kavin"
int(80)
bool(true)
How It Works
- PHP evaluates the right side first:
72 + 8becomes80. - It then stores the result in the variable on the left side.
- Any previous value in the variable is replaced.
Important:
=does not mean "equals" in the mathematical sense.$score = $score + 10is perfectly valid: it reads the current value, adds 10, and stores the new value. Comparisons use==or===.
Assignment Is an Expression
An assignment produces a value — the value that was assigned. This allows assignments inside larger expressions.
Example
<?php
$total = ($subtotal = 400) + 50;
echo "Subtotal: $subtotal, Total: $total\n";
$a = $b = $c = 0;
var_dump($a, $b, $c);
Output
Subtotal: 400, Total: 450
int(0)
int(0)
int(0)
How It Works
($subtotal = 400)assigns400and evaluates to400, which is then added to50.=is right-associative:$a = $b = $c = 0is evaluated as$a = ($b = ($c = 0)), so all three variables receive0.
Chained assignment is handy for initializing several counters. Assignments buried inside complex expressions, however, are hard to read; use them deliberately (see the loop pattern below) rather than to save a line.
Compound Assignment Operators
A compound operator applies an operation to the variable's current value and stores the result back in the same variable.
| Operator | Equivalent To | Purpose |
|---|---|---|
$a += $b | $a = $a + $b | Add |
$a -= $b | $a = $a - $b | Subtract |
$a *= $b | $a = $a * $b | Multiply |
$a /= $b | $a = $a / $b | Divide |
$a %= $b | $a = $a % $b | Remainder |
$a **= $b | $a = $a ** $b | Power |
$a .= $b | $a = $a . $b | Append a string |
$a ??= $b | $a = $a ?? $b | Assign only if $a is null or undefined (PHP 7.4+) |
$a &= $b, |=, ^=, <<=, >>= | $a = $a & $b, … | Bitwise operations |
Example: Arithmetic Compound Operators
<?php
$count = 10;
$count += 5; echo "+= 5 → $count\n";
$count -= 3; echo "-= 3 → $count\n";
$count *= 2; echo "*= 2 → $count\n";
$count /= 4; echo "/= 4 → $count\n";
$count %= 4; echo "%= 4 → $count\n";
$count **= 3; echo "**= 3 → $count\n";
var_dump($count);
Output
+= 5 → 15
-= 3 → 12
*= 2 → 24
/= 4 → 6
%= 4 → 2
**= 3 → 8
int(8)
Each line reads the current value, applies the operation, and stores the result. The type follows the normal arithmetic rules: 24 / 4 divides evenly, so the result stays an integer.
Why Use Compound Operators?
- Less repetition:
$orderTotals[$customerId] += $amountis shorter and less error-prone than repeating the long left side. - Clear intent:
+=immediately signals "add to the existing value". - The target is evaluated once: with complex targets such as
$data[$key()]['total'], the compound form evaluates the target expression a single time.
String Append: .=
.= appends text to the end of a string variable. It is the standard way to build output step by step.
<?php
$skills = ['PHP', 'MySQL', 'Git'];
$html = "<ul>\n";
foreach ($skills as $skill) {
$html .= " <li>" . htmlspecialchars($skill) . "</li>\n";
}
$html .= "</ul>";
echo $html;
Output
<ul>
<li>PHP</li>
<li>MySQL</li>
<li>Git</li>
</ul>
The variable must exist before the first .=; otherwise PHP raises an "Undefined variable" warning. Initialize it with "" or with the opening text.
Null Coalescing Assignment: ??=
$a ??= $b assigns $b only when $a is null or does not exist. Existing non-null values — including 0, "", and false — are kept.
<?php
$options = ['perPage' => 0, 'sort' => null];
$options['perPage'] ??= 20;
$options['sort'] ??= 'newest';
$options['theme'] ??= 'light';
var_dump($options);
Output
array(3) {
["perPage"]=>
int(0)
["sort"]=>
string(6) "newest"
["theme"]=>
string(5) "light"
}
perPageis0, which is notnull, so it is kept.sortisnull, so the default is assigned.themedoes not exist, so it is created — without any "Undefined array key" warning.
??= is ideal for filling defaults into configuration arrays and lazily initializing values. The ?? operator itself is covered in Null Coalescing Operator.
Bitwise Compound Assignment
Bitwise compound operators update flags stored in an integer:
<?php
const NOTIFY_EMAIL = 1;
const NOTIFY_SMS = 2;
const NOTIFY_PUSH = 4;
$settings = NOTIFY_EMAIL;
$settings |= NOTIFY_PUSH; // turn on push
$settings &= ~NOTIFY_EMAIL; // turn off email
var_dump(($settings & NOTIFY_PUSH) !== 0);
var_dump(($settings & NOTIFY_EMAIL) !== 0);
Output
bool(true)
bool(false)
Bitwise operators are explained in PHP Operators.
Assignment Inside Conditions
Because an assignment returns its value, you can assign and test in one expression. This is common in loops that read data until there is none left.
Example: Processing a Queue
<?php
$queue = ['send-email', 'resize-image', 'update-index'];
while (($task = array_shift($queue)) !== null) {
echo "Processing: $task\n";
}
Output
Processing: send-email
Processing: resize-image
Processing: update-index
How It Works
array_shift()removes and returns the first element, ornullwhen the array is empty.($task = array_shift($queue))stores the result in$taskand evaluates to it.!== nullchecks whether a task was returned.
The same pattern appears with fgets() when reading files line by line and with database result sets.
The Missing-Parentheses Bug
<?php
$text = "inbox";
if ($pos = strpos($text, "x") !== false) {
var_dump($pos);
}
if (($pos = strpos($text, "x")) !== false) {
var_dump($pos);
}
Output
bool(true)
int(4)
In the first condition, !== has higher precedence than =, so PHP evaluates strpos(...) !== false first and assigns the boolean result to $pos. The parentheses in the second condition make the assignment happen first, so $pos receives the position 4. Always wrap an assignment in parentheses when it is part of a comparison.
Assignment by Value vs by Reference
By Value (Default)
<?php
$prices = [100, 200];
$copy = $prices;
$copy[] = 300;
echo count($prices) . " / " . count($copy) . "\n";
Output
2 / 3
Assigning an array creates an independent copy (PHP uses copy-on-write internally, so the copy is cheap until it is modified). Strings, numbers, and booleans behave the same way.
By Reference: =&
<?php
$status = "draft";
$alias = &$status;
$alias = "published";
echo $status . "\n";
Output
published
$alias = &$status makes both names refer to the same value. References are useful in specific cases (for example, modifying array elements in foreach), but they make code harder to follow. Prefer normal assignment and return values.
Objects Are Handles
Objects behave differently: assigning an object copies a handle to the same object, so changes are visible through both variables even without &.
<?php
$product = new stdClass();
$product->name = "Lamp";
$same = $product;
$same->name = "Desk Lamp";
$copy = clone $product;
$copy->name = "Floor Lamp";
echo $product->name . "\n";
echo $copy->name . "\n";
Output
Desk Lamp
Floor Lamp
Use clone when you need an independent copy of an object. This is explained in Object Cloning.
Destructuring Assignment
Array destructuring assigns several variables from an array in one statement.
<?php
[$first, $second] = ['Asha', 'Bala'];
$user = ['name' => 'Charu', 'city' => 'Salem'];
['name' => $name, 'city' => $city] = $user;
$x = 1;
$y = 2;
[$x, $y] = [$y, $x];
echo "$first, $second\n";
echo "$name lives in $city\n";
echo "x = $x, y = $y\n";
Output
Asha, Bala
Charu lives in Salem
x = 2, y = 1
The last example swaps two variables without a temporary variable: the right side builds [2, 1] first, and then the values are assigned. Destructuring is covered in Array Destructuring.
Precedence: = vs and / or
The assignment operator has higher precedence than the word operators and, or, and xor, but lower precedence than && and ||:
<?php
$result1 = true && false;
$result2 = true and false;
var_dump($result1);
var_dump($result2);
Output
bool(false)
bool(true)
$result2 = true and false is evaluated as ($result2 = true) and false, so $result2 becomes true. Use && and || in assignments, or add parentheses. See Logical Operators.
Practical Example: Building an Order Report
<?php
$orders = [
['id' => 101, 'amount' => 1200, 'status' => 'paid'],
['id' => 102, 'amount' => 800, 'status' => 'refunded'],
['id' => 103, 'amount' => 450, 'status' => 'paid'],
['id' => 104, 'amount' => 3000, 'status' => 'paid'],
];
$paidCount = $revenue = $refunds = 0;
$report = "Order report\n";
foreach ($orders as $order) {
if ($order['status'] === 'paid') {
$paidCount += 1;
$revenue += $order['amount'];
} else {
$refunds += $order['amount'];
}
$report .= sprintf("#%d %-9s ₹%d\n", $order['id'], $order['status'], $order['amount']);
}
$report .= "Paid orders: $paidCount\n";
$report .= "Revenue: ₹$revenue\n";
$report .= "Refunds: ₹$refunds\n";
$report .= "Net: ₹" . ($revenue - $refunds) . "\n";
echo $report;
Output
Order report
#101 paid ₹1200
#102 refunded ₹800
#103 paid ₹450
#104 paid ₹3000
Paid orders: 3
Revenue: ₹4650
Refunds: ₹800
Net: ₹3850
Step-by-Step Explanation
$paidCount = $revenue = $refunds = 0;initializes three accumulators at once with chained assignment.- Inside the loop,
+=accumulates totals and counts, and.=appends one formatted line per order. %-9sleft-aligns the status in a 9-character column so the amounts line up.- After the loop, more lines are appended with
.=, and the finished report is printed once.
Building a string with .= and outputting it at the end makes it easy to send the same report by email, write it to a file, or return it from a function.
Common Mistakes
Using = Instead of ===
Effect: if ($status = 'paid') assigns the value and is always true.
Fix: Use === for comparisons. Some teams write "Yoda conditions" ('paid' === $status), which turn an accidental = into a parse error, but modern editors and static analysis tools flag the mistake anyway.
Compound Assignment on an Undefined Variable
Effect: $total += 10; without initializing $total raises "Undefined variable" (PHP treats it as null, so the result is 10).
Fix: Initialize accumulators before loops: $total = 0;.
Missing Parentheses When Assigning in a Condition
Effect: The variable receives a boolean instead of the intended value.
Fix: if (($pos = strpos(...)) !== false).
Using and / or in Assignments
Effect: $ok = $a and $b; assigns only $a.
Fix: Use && / ||.
Expecting Object Assignment to Copy
Effect: Changing the "copy" changes the original.
Fix: Use clone.
Using ??= When 0 or "" Should Be Replaced
Effect: ??= keeps 0, "", and false, because they are not null.
Fix: Use an explicit condition when empty values must also be replaced.
Best Practices
- Initialize variables (especially accumulators) before updating them.
- Use compound operators (
+=,.=,??=) to express updates clearly. - Wrap assignments in parentheses whenever they appear inside conditions.
- Prefer assignment by value; use references only for specific needs.
- Use
clonefor independent object copies. - Use
&&and||(notand/or) in expressions that assign results.
Official reference: https://www.php.net/manual/en/language.operators.assignment.php