How to read a user's input to the PHP console

What is a PHP console?

A PHP console is a command-line interface for writing and executing PHP codes. A PHP console is usually called the PHP interactive shell.

If you have PHP installed, you can access the console with the terminal command below:

php -a

However, it is more difficult to get user input through the PHP console as compared to using web browsers for input.

Prompting users for input

To get input from users, we also have to prompt them to enter something. We can use PHP’s `readline() function to get this input from the console.

What is the readline() function?

readline() is a built-in function in PHP that enables us to read input from the console. The function accepts an optional parameter that contains text to display.

Syntax

readline('input your name');

Code

The code below shows how we can read a single input from the user. Use the following command to execute the code:

php index.php

Note: Click the "Run` button to open the terminal.

<?php
  
// Input section
// get users name
$name = (string)readline("Your name: ");

$int = (int)readline('Enter an integer: ');
 
$float = (float)readline('Enter a floating'
            . ' point number: ');
 
// Entered integer is 10 and
// entered float is 9.78
echo "Hello ".$name.". The integer value you entered is " 
. $int
    . " and the float value is " . $float;
?>
Read a single line

As the code executes, we can see how the readline() function sends prompts to the console in order to take inputs.

Remember that to successfully execute this script on the command line, you must have added PHP to your system environment path.

Accepting multiple inputs

The readline() function can also help you accept multiple inputs, which are separated by some delimiter.

To achieve this, we must use another function called explode() together with readline(). The first argument of explode() is the delimiter that we want to use. The second argument will be the readline() function.

The code below shows how to accept multiple inputs from the console.Use the following command to execute the code:

php index.php

Note: Click the "Run` button to open the terminal.

<?php

// For input
// 1 2 3 4 5 6
$arr = explode(' ', readline());
 
// For output
print_r($arr)

?>
Read multiple lines