Arithmetic and assignment operators
Operators are signs that act on values. Remember from Secondary 1 that a program changes data step by step; here is the PHP version, taught from the start. The arithmetic operators are + - * / and %. The sign / divides, and two whole numbers can give a decimal: 7 / 2 is 3.5. The sign % gives the remainder: 10 % 3 is 1, because 3 goes into 10 three times and 1 is left. The assignment operators are shortcuts. $x += 5 means $x = $x + 5. In the same way -=, *=, /= and %= use the old value of $x. $x++ adds 1 and $x-- subtracts 1. To follow a program, make a trace table: after each line write the new value of the variable. In PHP 8 write these signs exactly: a space inside %= or a dash for -- is a syntax error.
| Operator | Example | Result |
|---|---|---|
| + | 7 + 2 | 9 |
| - | 7 - 2 | 5 |
| * | 7 * 2 | 14 |
| / | 7 / 2 | 3.5 |
| % | 7 % 2 | 1 |
1<?php 2echo 8 / 2, " ", 10 % 3, " ", 7 / 2; 3?>
4 1 3.5
1<?php 2$x = 10; 3$x += 5; echo $x, " "; 4$x -= 3; echo $x, " "; 5$x *= 2; echo $x, " "; 6$x /= 4; echo $x, " "; 7$x %= 4; echo $x, " "; 8$x++; echo $x, " "; 9$x--; echo $x; 10?>
15 12 24 6 2 3 2
| Line | Means | $x after |
|---|---|---|
| $x = 10; | start | 10 |
| $x += 5; | $x = $x + 5 | 15 |
| $x -= 3; | $x = $x - 3 | 12 |
| $x *= 2; | $x = $x * 2 | 24 |
| $x /= 4; | $x = $x / 4 | 6 |
| $x %= 4; | $x = $x % 4 | 2 |
| $x++; | add 1 | 3 |
| $x--; | subtract 1 | 2 |
On paper trace $n after each line: $n = 20; $n -= 6; $n *= 3; $n %= 5; $n++; Make a table with the line, what it means and the new value. Then check by computing it a second way.