Menu
Coddy logo textTech

Getting User Input

Part of the Fundamentals section of Coddy's PHP journey — lesson 13 of 71.

As of now we stored values that we thought about in variables. Programs usually don't work this way. We receive values from an outer source, a user for example.

To get input from a user or the system we need to write:

$var = trim(fgets(STDIN));

This will store the input in the variable $var — a placeholder name for any variable you choose to store the input in.

  • fgets(STDIN) — reads a line of input; STDIN means standard input (typically the keyboard or a data stream)
  • trim()trim means to cut off; it removes extra whitespace and newlines from the beginning and end of the input

The input is always of type string. For example, if the input is 56 then $var will hold the string "56".

challenge icon

Challenge

Easy

Read input from the system into the variables userName and the userAge.

If you are stuck look at the hint!

Cheat sheet

To get input from a user or the system in PHP:

$var = trim(fgets(STDIN));
  • fgets(STDIN) reads the input
  • trim() removes extra whitespace and newlines

Note: The input is always of type string. For example, if the input is 56 then the variable will hold the string "56".

Try it yourself

<?php
// Read input using trim(fgets(STDIN));
$userName = ?;
$userAge = ?;

echo "Hey " . $userName . "\n";
echo "You are " . $userAge . " years old.";
?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals