Task Two - Text Input and Output - PHP Tutorial

This program prompts you for your name, reads whatever you type and then replies with Hello {whatever you typed}.

Most programs include INPUT, PROCESSING and OUTPUT. This programs inputs your name, processes it by adding "Hello" and outputs the result.

Here is the result of running the program.

Here is the program code.


<?php

// ===== INPUT ========================
echo "\n\nWhat is your name ? ... ";
$name = fgets(STDIN);

// ===== PROCESS   ====================
$output = "Hello " . $name;

// ===== OUTPUT =======================
echo "\n\n$output\n\n\n";

?>

Code

Explanation

// INPUT

echo "\n\nWhat is your name ? ... ";

echo is used to display text. \n gives you a new line.

$name = fgets(STDIN);

$name is a variable. Think of this as a pigeon hole where text or other data can be stored. All variable names in PHP must begin with a $ sign.

fgets(); is a function call. Functions perform useful tasks and are often used many times and in many different programs. The fgets() function reads text from a file. STDIN is a special file reference that points to the keyboard. It gets all the text you enter on the keyboard until you press Enter. When you press Enter, the text read by fgets(STDIN) is copied into the $name pigeon hole/variable. STDIN means "standard input".

= is used for assignment statements. Assignment statments copy the result of the code to the right of the = sign onto the variable to the left of the = sign. In this case the result of fgets(STDIN) is copied into the $name variable. If you type "Fred", this name will be stored in $name.

// PROCESS

$output = "Hello " . $name;

  • The "." is an operator used to join text together.
  • "Hello " is joined to the text stored in the $name variable/pigeon hole.
  • The joined text is assigned to the $answer variable/pigeon hole.
  • If you typed "Fred" then "Hello Fred" is stored into $answer.

// OUTPUT

echo "\n\n$output\n\n\n";

This line displays text. It displays

  • two blank lines ( \n gives a blank line )
  • the contents of the $output variable/pigeon hole
  • three blank lines

 

Learning Task

Extend the program to hold a longer conversation. Use more variables.