PHP: Read until the end

Sometimes you do not know how many lines come. Read until the input ends.

What to build

A program that summarises a list of numbers, one per line.

Requirements

  • Read lines until the input ends. Ignore blank lines. Every other line holds one integer.
  • Print Count: N, Min: X, Max: Y and Sum: S.

Input

Any number of lines, each with one integer, possibly with blank lines between.

Output

Four lines.

Constraints

At least one number; at most 1000 numbers; each between -100000 and 100000.

Example

Input:

5
3
9
1
-4

Output:

Count: 5
Min: -4
Max: 9
Sum: 14

Why it works

A strict test against false stops exactly at the end of the input, and skipping blank lines keeps the data clean.

Examples

Example 1 · Input
5
3
9
1
-4
Expected output
Count: 5
Min: -4
Max: 9
Sum: 14
Example 2 · Input
42
Expected output
Count: 1
Min: 42
Max: 42
Sum: 42

Hints

Hint 1

Loop with while (($line = fgets(STDIN)) !== false) and trim each line.

Hint 2

Skip blank lines, and keep the numbers in an array so you can use min, max and array_sum.

Solution

Show one correct solution (try it yourself first)
<?php
$nums = [];
while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
    if ($line === "") {
        continue;
    }
    $nums[] = (int) $line;
}
echo "Count: ", count($nums), "\n";
echo "Min: ", min($nums), "\n";
echo "Max: ", max($nums), "\n";
echo "Sum: ", array_sum($nums), "\n";

▶ Open this solution in the compiler

Lesson: Input from STDIN →