Assignment Operators

sa sahaya jerish Updated 17 Oct 2026
10 min read ·Lesson 84 of 109
In this post

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

  1. PHP evaluates the right side first: 72 + 8 becomes 80.
  2. It then stores the result in the variable on the left side.
  3. Any previous value in the variable is replaced.

Important: = does not mean "equals" in the mathematical sense. $score = $score + 10 is 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) assigns 400 and evaluates to 400, which is then added to 50.
  • = is right-associative: $a = $b = $c = 0 is evaluated as $a = ($b = ($c = 0)), so all three variables receive 0.

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.

OperatorEquivalent ToPurpose
$a += $b$a = $a + $bAdd
$a -= $b$a = $a - $bSubtract
$a *= $b$a = $a * $bMultiply
$a /= $b$a = $a / $bDivide
$a %= $b$a = $a % $bRemainder
$a **= $b$a = $a ** $bPower
$a .= $b$a = $a . $bAppend a string
$a ??= $b$a = $a ?? $bAssign 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] += $amount is 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"
}
  • perPage is 0, which is not null, so it is kept.
  • sort is null, so the default is assigned.
  • theme does 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

  1. array_shift() removes and returns the first element, or null when the array is empty.
  2. ($task = array_shift($queue)) stores the result in $task and evaluates to it.
  3. !== null checks 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

  1. $paidCount = $revenue = $refunds = 0; initializes three accumulators at once with chained assignment.
  2. Inside the loop, += accumulates totals and counts, and .= appends one formatted line per order.
  3. %-9s left-aligns the status in a 9-character column so the amounts line up.
  4. 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 clone for independent object copies.
  • Use && and || (not and / or) in expressions that assign results.

Official reference: https://www.php.net/manual/en/language.operators.assignment.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators
Ask about this post
AI Ask about this post

Ask questions about Assignment Operators and get answers drawn from it.

Signed-in readers only.