What you will learn
- Use arithmetic operators including /, %, **, and
intdiv(). - Explain precedence and use parentheses to make intent clear.
- Recognize floating-point limitations.
- Build multi-step calculations from named intermediate values.
The code from this chapter
Type these programs yourself. The predictions below are the exercises; the explanations are in the book.
3.1 Arithmetic Operators
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$total = 12 + 5;
$total -= 2;
$total *= 3;
echo $total . PHP_EOL;
echo (17 % 5) . PHP_EOL;
3.2 Precedence and Parentheses
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$unitPrice = 4.50;
$quantity = 3;
$shipping = 6.00;
echo ($unitPrice * $quantity + $shipping) . PHP_EOL;
echo ($unitPrice * ($quantity + $shipping)) . PHP_EOL;
3.3 Floating-Point Reality
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$sum = 0.1 + 0.2;
var_dump($sum === 0.3);
echo $sum . PHP_EOL;
echo number_format($sum, 2) . PHP_EOL;
TPRM Lab 3.1: Division, Remainder, and Power
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$a = 17;
$b = 5;
echo ($a / $b) . PHP_EOL;
echo intdiv($a, $b) . PHP_EOL;
echo ($a % $b) . PHP_EOL;
echo (2 ** 4) . PHP_EOL;
TPRM Lab 3.2: Invoice Calculation
Type this into a file, predict the output, then run it.
<?php
declare(strict_types=1);
$unitPrice = 19.95;
$quantity = 3;
$taxRate = 0.13;
$subtotal = $unitPrice * $quantity;
$tax = $subtotal * $taxRate;
$total = $subtotal + $tax;
echo "Subtotal: $" . number_format($subtotal, 2) . PHP_EOL;
echo "Tax: $" . number_format($tax, 2) . PHP_EOL;
echo "Total: $" . number_format($total, 2) . PHP_EOL;