This tutorial explains the range of math and assignment operators available in the PHP programming language as well as operation precedence.
The main assignment and arithmetic operators you can use in PHP are:
- = (equals is an assignment operator)
- + (addition operator)
- – (subtraction operator)
- * (multiplication operator)
- / (division operator)
- % (modulus, used for finding the remainder from a division)
Example: $total = $num1 + $num2
You can also assign a value from a calculation using these operators:
- += (this means add and assign to eg. $total += 5 means to add 5 on to the value in the $total variable)
- -= (subtract)
- *= (multiply)
- /= (divide)
- %= (modulus)
Example: $total += $num3
Other operators include:
- ++ (increment by 1)
- — (decrement by 1)
Watch the video below and then scroll down to see some of the sample code.
This video explains math and assignment operators. The next video explains comparison and logical operators.
Sample PHP code:
<?php $number = 5; // the assignment operator $number = $number + 4; // the addition operator $number = $number - 4; // the subtraction operator $number = $number * 4; // the multiplication operator $number = $number / 4; // the division operator $number = $number % 4; // the modulus operator $number += 4; // example of addition & assignment shortcut // other examples include -= , *= , /= , and %= $number ++; // increment $number --; // decrement $number = (2 + 4) * 3; // brackets used (example of operation precedence) ?>
PHP Manual references: