php · level 1 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
PHP is a calculator that never gets tired.
+ adds, - takes away, * multiplies and / divides. Each of these symbols is an . PHP does * and / before + and -, like school maths, and brackets go first of all.
Dividing can give a number with a decimal point, like 3.5. That kind of number is a . gettype calls it a double, an older name for the same thing.
For whole numbers, intdiv(7, 2) divides and drops the leftover, giving 3. The % operator gives the , the part left over, so 7 % 2 is 1.
<?php
$slices = 7;
$friends = 2;
echo $slices / $friends . "\n";
echo intdiv($slices, $friends) . "\n";
echo $slices % $friends . "\n"; Brackets change the order, so 2 + 3 * 4 is 14 but (2 + 3) * 4 is 20.
guess first
Share out the sweets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$sweets = 17;
$bags = 5;
echo $sweets % $bags . "\n";
your turn
Your turn. Fill the party bags.
Choose how many sweets there are and how many kids are coming, both as integers. Run it to share them out fairly, then test a few other numbers.
fix it
Two friends are splitting the bill. Something is off.
- The bill is 14 in total, so each friend should pay 7. Which part of line 4 happens first?
- PHP divides before it adds, so only the popcorn gets split. Group the adding together.
- Put brackets round the adding,
($tickets + $popcorn) / 2, then press run.
nailed it
you turned the computer into a calculator. :D
+,-,*and/are operators for maths.*and/go before+and-, unless brackets say otherwise.%gives the remainder, andintdivgives the whole number part.
new words in your collection
- operator
- float
- remainder
This lesson isn’t saved. A free account remembers every lesson you finish.