Input from STDIN

Introduction

A useful program does not always print the same thing. It reads data, works with it and prints a result that depends on that data. Here PHP works like the php command on a terminal: the data comes from the standard input, and in the compiler on this site it comes from the Input box. In this lesson you will learn the safe ways to read a line, a number, several numbers and everything until the input ends. Because input always arrives as text, you will also learn how to turn it into numbers.

How it works

The constant STDIN stands for the standard input. The function fgets(STDIN) reads one line, including the new line at the end. When there are no more lines, it returns false. Almost every program reads like this:

$name = trim(fgets(STDIN));
$n = (int) trim(fgets(STDIN));

trim removes the new line at the end, and (int) turns the text into a whole number. Without trim, comparing text would fail, because "Ada\n" is not "Ada".

To read several numbers from one line, there are two good ways. The first is fscanf, which works like scanf in C:

fscanf(STDIN, "%d %d", $a, $b);

The format says: two integers separated by a space. The values are stored in $a and $b. Use %s for a word and %f for a decimal number. The second way is to split the line yourself: explode(" ", trim(fgets(STDIN))) gives an array of words, and array_map('intval', ...) turns every word into an int.

When you do not know how many lines there are, loop until fgets returns false:

while (($line = fgets(STDIN)) !== false) {
    $line = trim($line);
}

The extra brackets and !== false matter. A line that contains only 0 is falsy in PHP, so a plain while ($line = fgets(STDIN)) could stop too early.

PHP also has readline(), which reads one line without the new line at the end. It is nice and short, but do not mix readline() and fgets(STDIN) in one program. Choose one way and use it everywhere. All examples in this course use fgets(STDIN).

Example

<?php
$name = trim(fgets(STDIN));
fscanf(STDIN, "%d %d", $a, $b);
$n = (int) trim(fgets(STDIN));
$nums = array_map('intval', explode(" ", trim(fgets(STDIN))));

echo "Hello, $name!\n";
echo "Sum of $a and $b is ", $a + $b, "\n";
echo "Next number: ", $n + 1, "\n";
echo "Total: ", array_sum($nums), " from ", count($nums), " numbers\n";

$line = fgets(STDIN);
if ($line === false) {
    echo "No more input\n";
}

Input used: Ada ⏎ 3 4 ⏎ 5 ⏎ 10 20 30

Line by line

  1. fgets reads the first line and trim removes the line break, so $name is Ada.
  2. fscanf reads the line 3 4 into $a and $b as numbers.
  3. The next line is read as text and cast to an int.
  4. The last line is split on spaces and every part is turned into an int.
  5. The program prints a greeting, a sum, the next number and the total of the list.
  6. The input has ended, so fgets returns false, and the program says so.

Expected result

With this input:

Ada
3 4
5
10 20 30

it prints:

Hello, Ada!
Sum of 3 and 4 is 7
Next number: 6
Total: 60 from 3 numbers
No more input

In the real world

Command line tools read from the input all the time: a script can receive data from another program through a pipe, or from a file. Contest sites and automatic graders also give a program its data through the standard input and check the printed output. Reading input carefully, and handling the end of the data, is the same skill in both cases.

Common mistakes

  • Forgetting trim, so a stray new line breaks a comparison or a number.
  • Using while ($line = fgets(STDIN)) and stopping early on a line that contains 0.
  • Mixing readline() and fgets(STDIN) in one program.
  • Treating numbers as numbers before converting them. The text "10" and the number 10 behave differently in some places.

Best practices

  • Read with trim(fgets(STDIN)) and convert at once with (int) or (float).
  • Test the end of input with === false or !== false.
  • Use explode with array_map when a line holds many numbers.
  • Choose one reading style for the whole program.

Summary

fgets(STDIN) reads one line and returns false at the end of the input. Use trim to remove the line break and a cast to get a number. fscanf reads values with a format, and explode with array_map reads a list of numbers. Loop with !== false to read everything.

Quick check

1. What does fgets(STDIN) return when the input has ended?
2. Why do we call trim on a line from fgets?
3. What does fscanf(STDIN, "%d %d", $a, $b) do?
4. Which loop condition is the safe way to read all lines?

Key takeaways

  • fgets with trim reads a clean line, and a cast turns it into a number.
  • fscanf and explode read several values from one line.
  • Loop until fgets returns false to read all the input.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.