0
0
PHPprogramming~5 mins

Assignment and compound assignment in PHP

Choose your learning style9 modes available
Introduction

Assignment lets you store a value in a variable. Compound assignment helps you update that value easily.

When you want to save a number or text to use later.
When you want to add or subtract from a number stored in a variable.
When you want to multiply or divide a variable's value by another number.
When you want to quickly update a variable without writing it twice.
Syntax
PHP
$variable = value;
$variable += value;
$variable -= value;
$variable *= value;
$variable /= value;

The single equals sign = assigns a value to a variable.

Compound assignments like += combine an operation and assignment in one step.

Examples
This sets the variable $x to 10.
PHP
$x = 10;
This adds 5 to the current value of $x.
PHP
$x += 5;  // same as $x = $x + 5;
This multiplies $x by 2 and stores the result back in $x.
PHP
$x *= 2;  // same as $x = $x * 2;
Sample Program

This program shows how to assign and update a variable using assignment and compound assignment operators.

PHP
<?php
$x = 10;
echo "Initial value: $x\n";

$x += 5;
echo "After adding 5: $x\n";

$x *= 3;
echo "After multiplying by 3: $x\n";

$x -= 4;
echo "After subtracting 4: $x\n";

$x /= 2;
echo "After dividing by 2: $x\n";
?>
OutputSuccess
Important Notes

Compound assignments save time and make code easier to read.

Be careful with division; dividing integers can result in floats.

Summary

Use = to assign values to variables.

Use compound assignments like +=, -=, *=, /= to update variables quickly.