readline() reads an interactive line of input from a terminal. This guide explains the function with focused examples and the decisions that matter in real applications.
What Is readline() in PHP?
Reads an interactive line of input from a terminal.
A typical call looks like this:
<?php
readline([$prompt]);
The input arguments shown in the call identify the relevant connection, resource, value, path or configuration for the operation. Pay attention to argument order and to the return value demonstrated below.
Example 1: Basic Usage
This first example uses readline() directly to demonstrate its basic purpose.
<?php
$name = readline("Your name: "); echo "Hello $name";
The returned value illustrates reads an interactive line of input from a terminal. It is a CLI operation and may block waiting for user input.
Example 2: A Different Input or Option
The next example changes the input or option, showing another supported use of readline().
<?php
$answer = readline("Continue? [y/N] "); echo strtolower(trim($answer)) === "y" ? "Continue" : "Stop";
The returned value illustrates reads an interactive line of input from a terminal. It is a CLI operation and may block waiting for user input.
Practical Example: Applying the Function
In application code, readline() belongs in a controlled workflow with input validation, a checked result and cleanup where needed.
<?php
$value = readline("Enter a number: "); if (filter_var($value, FILTER_VALIDATE_INT) !== false) echo "Valid integer";
The returned value illustrates reads an interactive line of input from a terminal. It is a CLI operation and may block waiting for user input.
Important Behavior and Edge Cases
- Main behavior: Reads an interactive line of input from a terminal.
- Important limitation: It is a CLI operation and may block waiting for user input.
- Requirements: This function uses the CLI readline extension; it is not designed for an ordinary web request.
Comparison With Related Functions
| Function or Approach | When to Use It |
|---|---|
readline() | Reads an interactive line of input from a terminal. |
fgets | Reads a line from a stream and can be used when terminal readline facilities are unavailable. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
Ignoring the specific limits or preconditions of readline(). | It is a CLI operation and may block waiting for user input. |
| Assuming every environment produces the same result. | This function uses the CLI readline extension; it is not designed for an ordinary web request. |
Key Takeaways
- Reads an interactive line of input from a terminal.
- It is a CLI operation and may block waiting for user input.
- This function uses the CLI readline extension; it is not designed for an ordinary web request.
Use readline() when its behavior matches your task, and verify the relevant return value before taking further action. The output depends on the local configuration when it uses resources, files or an interactive terminal.