← Back to Chapters

PHP Assignment Operators

? PHP Assignment Operators

? Quick Overview

Assignment operators are used to assign values to variables. PHP offers shorthand assignment operators for performing operations and assigning the result in a single step.

? Key Concepts

  • = Assign
  • += Add and assign
  • -= Subtract and assign
  • *= Multiply and assign
  • /= Divide and assign
  • %= Modulus and assign

? Syntax & Theory

Assignment operators combine arithmetic operations with assignment. They help reduce repetitive code and improve readability by updating variable values directly.

? Code Example

? View Code Example
// Demonstrating PHP assignment operators step by step
<?php
$a = 10;
echo "Initial: $a<br>";

$a += 5;
echo "After += 5: $a<br>";

$a -= 3;
echo "After -= 3: $a<br>";

$a *= 2;
echo "After *= 2: $a<br>";

$a /= 4;
echo "After /= 4: $a<br>";

$a %= 3;
echo "After %= 3: $a<br>";
?>

? Live Output / Explanation

This script updates the same variable multiple times using different assignment operators. Each operation modifies the current value of the variable and prints the updated result.

? Interactive Playground

Change the starting value of $a to see how assignment operators update the result.

$a += 5 15
$a -= 3 7
$a *= 2 20
$a /= 2 5
$a %= 3 1

? Interactive Explanation

Think of assignment operators as shortcuts. Instead of rewriting the variable on both sides, PHP automatically applies the operation to the existing value.

? Use Cases

  • Updating counters and scores
  • Accumulating totals in loops
  • Performing incremental calculations

✅ Tips & Best Practices

  • Use assignment operators to make your code cleaner and shorter.
  • Use parentheses when mixing multiple operations.
  • Avoid overusing chained assignments for better readability.

? Try It Yourself

  • Create a file named assignment.php.
  • Initialize a variable and apply each assignment operator.
  • Print the value after every operation.