The readline() function is an inbuilt function in PHP that is used to read user input from the command line window. It provides a way to interactively prompt the user for input and capture their response as a string.
Syntax:
readline($prompt): string|false
Parameters: This function accepts one parameter which is described below.
- $prompt: This is an optional parameter. This is the string parameter that is displayed when the user entered the command line interface.
Return Value: The readline() function returns the provided string. This function will return false if no more data is found to be read.
Program 1: The following program demonstrates the readline() function.
PHP
<?php // Simple example prompting the user for their name $name = readline( "Enter your name: " ); // Check if the user provided a name if ( $name !== "" ) { echo "Hello, $name! Nice to meet you." ; } else { echo "You didn't enter your name." ; } ?> |
Enter your name: Hello, ! Nice to meet you.
Program 2: The following program demonstrates the readline() function.
PHP
<?php // Function to ask a question and get user input function askQuestion( $question ) { return readline( $question . " " ); } // Main program echo "Welcome to the Interactive Survey!\n" ; echo "Please answer the following questions:\n" ; // Ask the user some questions $name = askQuestion( "1. What is your name?" ); $age = askQuestion( "2. How old are you?" ); $location = askQuestion( "3. Where are you from?" ); $hobby = askQuestion( "4. What is your favorite hobby?" ); $feedback = askQuestion( "5. How do you like this survey?" ); // Display the survey results echo "\nSurvey Results:\n" ; echo "Name: {$name}\n" ; echo "Age: {$age}\n" ; echo "Location: {$location}\n" ; echo "Favorite Hobby: {$hobby}\n" ; echo "Feedback: {$feedback}\n" ; echo "\nThank you for participating in the survey!\n" ; ?> |
Output:
Welcome to the Interactive Survey!
Please answer the following questions:
1. What is your name? GFG
2. How old are you? 20
3. Where are you from? India
4. What is your favorite hobby? ID
5. How do you like this survey? bored
Survey Results:
Name: GFG
Age: 20
Location: India
Favorite Hobby: ID
Feedback: bored
Thank you for participating in the survey!
Reference: https://www.php.net/manual/en/function.readline.php