Learn/PHP/3. Reading input and arithmetic
Lesson 3 of 15
Sign in

PHP, lesson 3

Reading input and arithmetic

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.
  • When there are no more lines, fgets() returns false instead of a string. You'll use that to read "until the input ends" in the loops lesson.

Turning text into numbers

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.

Exercise 1

Pizza party

Press Ctrl Enter or Check to test your code.

Exercise 2

Road trip fuel

Press Ctrl Enter or Check to test your code.

(int) "12abc"
12
is_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.

Arithmetic operators

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
%remainder7 % 21
**power7 ** 249

Some PHP specifics:

  • / returns an int when both sides are integers and the division is exact (8 / 4 is 2), and a float otherwise.
  • For whole-number division, use intdiv(7, 2), which gives 3.
  • % works on integers, and the result takes the sign of the left operand: -7 % 2 is -1.
  • Dividing by zero with /, % 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.

Rounding for display

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.

Further reading

  • fgets()
  • CLI input and output streams
  • Arithmetic operators
  • intdiv()
  • number_format()

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.33
pizzas: 3
leftover: 2
11
2
pizzas: 3
leftover: 2
250 6.4 1.85
29.60