PHP, lesson 3
Command-line PHP gives you a ready-made handle for standard input called STDIN. The usual
way to read one line from it is fgets():
Two details matter:
fgets() keeps the newline at the end of the line, so you almost always wrap it in
trim(), which removes spaces and newlines from both ends.fgets() returns false instead of a string. You'll use that
to read "until the input ends" in the loops lesson.Input always arrives as a string. Convert it with a cast:
Casts never fail: (int) "abc" is simply 0, and is . That is forgiving
but can hide bad input. tells you whether a string really is a number; you'll
use it in the lesson on errors.
2 exercises to try what you just read.
(int) "12abc"12is_numeric()When several values share a line, split it with explode(), which cuts a string at every
occurrence of a separator and gives you an array:
For simple, well-formed input, fscanf() reads and converts in one step:
fscanf(STDIN, "%d %d", $a, $b); stores two integers in $a and $b.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
Some PHP specifics:
/ returns an int when both sides are integers and the division is exact (8 / 4 is
2), and a float otherwise.intdiv(7, 2), which gives 3.% works on integers, and the result takes the sign of the left operand: -7 % 2 is -1./, % or intdiv() throws a DivisionByZeroError.Shorthand updates work as you'd expect: $total += 5;, $count++;, $price *= 2;.
Integers are 64-bit on the systems you'll use, so they go up to about 9.2 × 10¹⁸. Beyond
that, PHP silently switches to float and loses precision.
To show a fixed number of decimals, use number_format() or printf():
number_format() also adds a thousands separator by default (1,234.50). round($x, 2)
rounds the value itself and returns a float. Use it for calculations, and the formatting
functions for display.
Every guest eats the same number of slices and each pizza has 8 slices. The first input line is the number of guests, the second is slices per guest. Print how many whole pizzas to order (enough for everyone) and how many slices will be left over, in this form:
Sample input:
Sample output:
Read three numbers from one line: the distance in km, the car's consumption in litres per 100 km, and the fuel price per litre. Print the cost of the trip with two decimals.
Sample input:
Sample output:
<?php
$name = trim(fgets(STDIN));
echo "Hi, $name!\n";<?php
$age = (int) trim(fgets(STDIN)); // "29" -> 29
$height = (float) trim(fgets(STDIN)); // "1.75" -> 1.75<?php
[$a, $b] = explode(" ", trim(fgets(STDIN))); // "3 4" -> "3", "4"
echo (int) $a + (int) $b, "\n";<?php
$share = 10 / 3;
echo number_format($share, 2), "\n"; // 3.33
printf("%.2f\n", $share); // 3.33pizzas: 3
leftover: 211
2pizzas: 3
leftover: 2250 6.4 1.8529.60