AdvertisementYour brand could be hereYour brand hereOn every Darslab page · students, parents and teachersinfo@darslab.comAsk for pricesPricesinfo@darslab.com
☰ Year plan · Communication Technology

Operators and the if statement

Week 12 · Unit 3 Creating Site Pages (5), Topic 2 Operators and conditional statements in PHP: arithmetic, assignment, comparison and logical operators, if, else, elseif and the in-line if · 3 lessons
1

Arithmetic and assignment operators

ICT Secondary 2 Term 1, Unit 3, Topic 2: pp. 86–92
GoalUse arithmetic and assignment operators and trace the value of a variable.
New words
operator · a sign that works on values, such as + or %remainder · what is left after dividing: 10 % 3 is 1assignment operator · an operator such as += that changes a variable using its own valueincrement and decrement · ++ adds 1 and -- subtracts 1
Explanation

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.

OperatorExampleResult
+7 + 29
-7 - 25
*7 * 214
/7 / 23.5
%7 % 21
Worked examples
Php
1<?php
2echo 8 / 2, " ", 10 % 3, " ", 7 / 2;
3?>
Output
4 1 3.5
Division and remainder. The first number is 8 / 2 = 4, then 10 % 3 = 1, then 7 / 2 = 3.5. The page shows the three results separated by spaces.
Php
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?>
Output
15 12 24 6 2 3 2
Trace table of $x. The code prints $x after each line, so the output lists the values in order: 15, 12, 24, 6, 2, 3 and then 2.
LineMeans$x after
$x = 10;start10
$x += 5;$x = $x + 515
$x -= 3;$x = $x - 312
$x *= 2;$x = $x * 224
$x /= 4;$x = $x / 46
$x %= 4;$x = $x % 42
$x++;add 13
$x--;subtract 12
The same trace as a table: each line, what it means, and the new value of $x.
Class activity

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.

Practice
1
What are 17 % 5 and 17 / 5?
2
What is $x after $x = 6; $x += 4; $x *= 2;?
3
How do you write “subtract 1 from $count”?
4
Why does 7 / 2 not give 3?