PHP Introduction | Operators | Arithmetic Operators

- $a

Reverses the sign of $a.

<?php
  $a = 10;
  echo - $a;
?>

Outputs -10.

$a + $b

Adds $a and $b.

<?php
  $a = 10;
  $b = 4;
  echo $a + $b;
?>

Outputs 14.

$a - $b

Subtracts $b from $a.

<?php
  $a = 10;
  $b = 4;
  echo $a - $b;
?>

Outputs 6.

$a * $b

Multiplies $a and $b.

<?php
  $a = 10;
  $b = 4;
  echo $a * $b;
?>

Outputs 40.

$a / $b

Divides $a by $b.

<?php
  $a = 10;
  $b = 4;
  echo $a / $b;
?>

Outputs 2.5.

$a % $b

Returns the remainder after dividing $a by $b.

<?php
  $a = 10;
  $b = 4;
  echo $a % $b;
?>

Outputs 2.

$a ** $b

Raises $a to the power of $b.

<?php
  $a = 4;
  $b = 3;
  echo $a ** $b;
?>

Outputs 64.

Operator Precedence When Using Multiple Operators

If parentheses are present, the expression inside the parentheses is calculated first.

  • *, /, and % are calculated in order.
  • + and - are calculated in order.
  • *, /, and % are calculated before + and -.
<?php
  $a = 4;
  $b = 3;
  $c = 2;
  echo ( $a + $b ) * $c;    // 14
  echo $a * $b / $c;        // 6
  echo $a + $b - $c;        // 5
  echo $a + $b * $c;        // 10
?>