Web Analytics

PHP Assignment Operators

Beginner~15 min read

Assignment operators are used to assign values to variables. PHP provides shortcuts called compound assignment operators that combine arithmetic operations with assignment, making your code more concise!

Assignment Operators Overview

Operator Example Equivalent To
= $x = 5 Simple assignment
+= $x += 3 $x = $x + 3
-= $x -= 3 $x = $x - 3
*= $x *= 3 $x = $x * 3
/= $x /= 3 $x = $x / 3
%= $x %= 3 $x = $x % 3
.= $x .= "y" $x = $x . "y"
Output
Click Run to execute your code

Simple Assignment (=)

<?php
$name = "John";
$age = 25;
$price = 19.99;

// Assignment returns the assigned value
$x = $y = $z = 10;  // All three are 10
?>

Addition Assignment (+=)

<?php
$count = 10;
$count += 5;  // Same as: $count = $count + 5
echo $count;  // 15

// Common use: incrementing counters
$total = 0;
$total += 100;
$total += 50;
echo $total;  // 150
?>

String Concatenation Assignment (.=)

<?php
$message = "Hello";
$message .= " World";  // Same as: $message = $message . " World"
echo $message;  // "Hello World"

// Building strings
$html = "<div>";
$html .= "<h1>Title</h1>";
$html .= "<p>Content</p>";
$html .= "</div>";
?>

Summary

  • =: Assign value to variable
  • +=: Add and assign
  • -=: Subtract and assign
  • *=: Multiply and assign
  • /=: Divide and assign
  • %=: Modulus and assign
  • .=: Concatenate and assign

What's Next?

Next, we'll explore Comparison Operators - essential for making decisions in your code by comparing values!