Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

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

NDUKWE CHIDERA K.

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, you also have to prompt them to enter something. You 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 you can read a single input from the user.

<?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;
?>

The result of executing the script above is as follows:

As the code executes, you 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, you must use another function called explode() together with readline(). The first argument of explode() is the delimiter you want to use. The second argument will be the readline() function.

The code below shows how to accept multiple inputs from the console:

<?php

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

?>

Your output will look like the image below.

RELATED TAGS

php
communitycreator
RELATED COURSES

View all Courses

Keep Exploring