php assignment operators

Part of the course: php for beginners

php assignment operators

1. Introduction to Assignment Operators in PHP

Assignment operators in PHP are used to assign values to variables. The most common assignment operator is the simple equal sign (=), which sets a variable to a specific value. However, PHP also provides several compound assignment operators that allow you to perform an operation and assign the result in one step.

For example, instead of writing a full expression like:

$x = $x + 5;

You can use an assignment operator to make it shorter:

$x += 5;

Assignment operators help make your code cleaner, faster to write, and easier to read. They are commonly used in loops, mathematical expressions, and string operations.

 

2. Basic Assignment Operator (=)

The basic assignment operator in PHP is the equal sign (=). It is used to assign a value to a variable. This operator does not mean equality (like in mathematics). Instead, it stores the value on the right-hand side into the variable on the left-hand side.

How it works

$variable = value;

PHP first evaluates the expression on the right, then assigns the result to the variable on the left.

Examples

Assigning a number

$x = 10;

The variable $x now holds the value 10.

Assigning a string

$name = "John";

Assigning the result of an expression

$y = 5 + 3; // $y becomes 8

Assigning one variable to another

$a = 20;
$b = $a; // $b now also holds 20

Key point

The assignment operator always works right to left, meaning the value on the right is assigned to the variable on the left.

3. Compound Assignment Operators

Compound assignment operators in PHP allow you to perform a mathematical operation and assign the result to the same variable in a shorter, cleaner way. Instead of writing the full expression (e.g., $x = $x + 5), you can combine the operator with = to simplify your code.

These operators improve readability and reduce repetition in your programs.

3.1 Addition Assignment (+=)

The += operator adds a value to an existing variable and then stores the result in that same variable.

Example:

$x = 10;
$x += 5; // $x becomes 15

3.2 Subtraction Assignment (-=)

The -= operator subtracts a value from an existing variable and assigns the result back to that variable.

Example:

$x = 20;
$x -= 7; // $x becomes 13

3.3 Multiplication Assignment (*=)

The *= operator multiplies a variable by a value and stores the result in that same variable.

Example:

$x = 4;
$x *= 3; // $x becomes 12

3.4 Division Assignment (/=)

The /= operator divides a variable by a value and updates the variable with the result.

Example:

$x = 20;
$x /= 4; // $x becomes 5

3.5 Modulus Assignment (%=)

The %= operator calculates the remainder of dividing a variable by a value and assigns the remainder back to the variable.

Example:

$x = 17;
$x %= 5; // $x becomes 2

3.6 Exponentiation Assignment (**=)

The **= operator raises a variable to the power of a value and assigns the exponent result back to the variable.

Example:

$x = 2;
$x **= 3; // $x becomes 8 (2³)

4. String Concatenation Assignment Operator (.=)

php assignment operators

php assignment operators

The string concatenation assignment operator in PHP (.=) is used to append (add) a string to an existing variable. It combines two strings and stores the result back into the same variable, making your code shorter and easier to read.

How it works

$variable .= "string";

This means:

$variable = $variable . "string";

Both lines produce the same result, but the .= operator is more efficient and cleaner.

Examples

Appending text to a string

$message = "Hello";
$message .= " World!";
// Result: "Hello World!"

Building a sentence step-by-step

$text = "PHP";
$text .= " is";
$text .= " powerful.";
// Result: "PHP is powerful."

Using variables with concatenation

$name = "John";
$greeting = "Hello, ";
greeting .= $name;
// Result: "Hello, John"

Why use .=?

  • Reduces repetitive code

  • Makes string-building cleaner

  • Commonly used in loops, text generation, and dynamic content creation

 

 

5. Bitwise Assignment Operators

Bitwise assignment operators in PHP allow you to perform bit-level operations on integers and then assign the result back to the same variable. These operators are useful when working with low-level programming tasks such as permissions, flags, binary data, and performance-critical operations.

Each operator performs a bitwise operation and then updates the variable with the new value.

5.1 Bitwise AND Assignment (&=)

The &= operator compares each bit of the variable with the corresponding bit of another value.
Only bits that are 1 in both values remain 1.

Example:

$x = 6; // 6 in binary: 110
$x &= 3; // 3 in binary: 011
// Result binary: 010 → 2

5.2 Bitwise OR Assignment (|=)

The |= operator sets a bit to 1 if that bit is 1 in either value.

Example:

$x = 4; // 100
$x |= 1; // 001
// Result: 101 → 5

5.3 Bitwise XOR Assignment (^=)

The ^= operator sets a bit to 1 only if the bits in the two values are different.
If they are the same, the bit becomes 0.

Example:

$x = 5; // 101
$x ^= 3; // 011
// Result: 110 → 6

5.4 Left Shift Assignment (<<=)

The <<= operator shifts the bits of the number to the left by a given number of positions.
Each shift multiplies the value by 2.

Example:

$x = 3; // 011
$x <<= 2; // shift left 2 positions
// Result: 1100 → 12

5.5 Right Shift Assignment (>>=)

The >>= operator shifts the bits of the number to the right by a given number of positions.
Each shift divides the value by 2 (ignoring decimals).

Example:

$x = 16; // 10000
$x >>= 2; // shift right 2 positions
// Result: 100 → 4

6. Examples of Using Assignment Operators in PHP

Assignment operators are used in many situations in PHP, such as updating values, performing calculations, working with strings, and manipulating data in loops. The following examples show how different assignment operators work in real code.

Example 1: Basic Assignment (=)

$x = 10;
$y = 20;
$result = $x + $y; // result = 30

This simply assigns values to variables and uses them in an expression.

Example 2: Addition Assignment (+=)

$score = 50;
$score += 10; // $score = 60

This is useful when increasing counters or scores.

Example 3: Subtraction Assignment (-=)

$balance = 100;
$balance -= 25; // $balance = 75

Commonly used when reducing a value (like deducting money or quantity).

Example 4: Multiplication Assignment (*=)

$price = 20;
$price *= 2; // $price = 40

Useful for scaling quantities or prices.

Example 5: Division Assignment (/=)

$distance = 100;
$distance /= 4; // $distance = 25

Example 6: Modulus Assignment (%=)

$number = 17;
$number %= 5; // remainder = 2

Example 7: Exponentiation Assignment (**=)

$x = 2;
$x **= 4; // 2^4 = 16

Example 8: String Concatenation Assignment (.=)

$name = "John";
$name .= " Doe";
// Result: "John Doe"

This is commonly used when building dynamic text.

Example 9: Bitwise Assignment

$x = 6; // 110 in binary
$x &= 3; // 011
// Result: 010 → 2

Example 10: Assignment Inside Loops

$sum = 0;
for ($i = 1; $i <= 5; $i++) {
$sum += $i;
}
echo $sum; // Output: 15

This shows how assignment operators are frequently used in loops to update values.

7. Common Mistakes and Best Practices

Using assignment operators in PHP is simple, but developers—especially beginners—often make certain mistakes. Understanding these issues and following best practices will help you write cleaner, safer, and more efficient code.

Common Mistakes

1. Confusing = with == or ===

A common mistake is using the assignment operator (=) when you actually want to compare values.

Incorrect (mistake):

if ($x = 5) { ... }

This assigns 5 to $x, and the condition becomes true, which can cause bugs.

Correct:

if ($x == 5) { ... }

2. Forgetting That Assignment Happens Right to Left

Some developers expect this to behave differently:

$x = $y = 10;

But the assignment actually works right to left:

  • $y becomes 10

  • Then $x becomes the value of $y10

3. Misusing Compound Operators on Strings

Using operators like += on strings can produce unexpected results (because += is for numbers).

Example:

$x = "10";
$x += 5; // becomes 15, because PHP converts "10" to a number

This type juggling can cause hidden bugs.

4. Unexpected Type Conversion

PHP automatically converts types when using assignment operators.

$x = "100";
$x /= 4; // becomes 25 (converted to integer)

Sometimes this is helpful, but it can also cause unintended results.

Best Practices

1. Use Compound Operators for Cleaner Code

Using operators like +=, -=, *=, .= makes your code shorter and easier to understand.

2. Be Careful with Mixed Data Types

Always know whether your variable is a string, integer, float, etc.

To avoid mistakes:

  • Use .= only for strings

  • Use +=, -=, *=, /=, etc. only for numbers

3. Avoid Assignment Inside Conditions (unless necessary)

It makes code harder to read and can introduce bugs.

Not recommended:

if ($x = 10) { ... }

4. Use Parentheses for Clarity

If combining assignment with other operations, parentheses improve readability:

$total += ($price * $quantity);

5. Comment Your Code When Using Complex Bitwise Assignments

Bitwise operations are not always obvious, so adding comments helps others (and your future self) understand the logic.

8. Conclusion

Assignment operators are a fundamental part of PHP programming. They allow you to assign values to variables, update them efficiently, and perform operations in a concise way. From the basic assignment operator (=) to compound operators like +=, -=, and .= for strings, these operators help make your code cleaner and easier to read.

By understanding and using assignment operators correctly, you can:

  • Write shorter, more readable code

  • Perform calculations and updates efficiently

  • Reduce errors and repetitive code

  • Work effectively with numbers, strings, and even bitwise operations

Remember to follow best practices, pay attention to data types, and avoid common mistakes such as confusing = with ==. Mastery of assignment operators is a small but important step toward writing professional, maintainable PHP code.