Arithmetic & Assignment Operators

Operators let you perform math and assign values to variables.

Syntax$x += 5; // same as $x = $x + 5;

Arithmetic operators perform common math operations:

  • + addition, - subtraction
  • * multiplication, / division
  • % modulus (remainder), ** exponentiation

Assignment operators

The basic assignment is =. Combined operators such as +=, -=, *= and .= update a variable in place.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Calculate the discounted subtotal using arithmetic operators before applying tax in a checkout flow.
  • Use += to accumulate a running total inside a loop that processes order line items.
  • Apply the modulo operator % to determine whether a loop iteration is even or odd for zebra-striping table rows.

More examples

Arithmetic operators

The five arithmetic operators perform the core math needed in pricing, percentage, and division calculations.

Example · php
<?php
$price    = 100;
$discount = 15;

$subtotal = $price - $discount;     // 85
$tax      = $subtotal * 0.1;        // 8.5
$total    = $subtotal + $tax;       // 93.5
$share    = $total / 2;             // 46.75
$leftover = 100 % 3;               // 1

echo number_format($total, 2);

Assignment operators

+= and its siblings (-=, *=, /=, %=) shorten the common read-modify-write pattern inside loops.

Example · php
<?php
$total = 0;
$items = [10, 25, 8, 42];

foreach ($items as $item) {
    $total += $item;  // equivalent to $total = $total + $item
}

echo $total; // 85

Modulo for even/odd rows

The modulo operator returns the remainder of division, making it the classic tool for alternating row classes.

Example · php
<?php
$rows = ['Alice', 'Bob', 'Carol', 'Dave'];

foreach ($rows as $i => $name) {
    $class = ($i % 2 === 0) ? 'even' : 'odd';
    echo "<tr class=\"$class\"><td>$name</td></tr>\n";
}

Discussion

  • Be the first to comment on this lesson.