Open In App

PHP readline_add_history() Function

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The readline_add_history() is an inbuilt function in PHP that is used to add a line to the command line history. 

Syntax:

readline_add_history($prompt): bool

Parameter: 

This function accepts only a single parameter that is described below.

  • $prompt: This is a string parameter that adds to a line in the command line history. It should be a string parameter.

Return Value: 

The return value of the readline_add_history() function is a boolean value. If this function successfully adds a line to the command line history, then it will return “true” otherwise on failure it will return “false”.

Program 1: The following program demonstrates the readline_add_history() Function.

PHP




<?php
readline_clear_history();
  
// Add lines to command line history
readline_add_history("First line");
readline_add_history("Second line");
readline_add_history("Third line");
  
// Retrieve command line history
$history = readline_list_history();
print_r($history);
?>


Output

Array
(
    [0] => First line
    [1] => Second line
    [2] => Third line
)

Program 2: The following program demonstrates the readline_add_history() Function.

PHP




<?php
  
readline_clear_history();
  
// Add lines to command line history
readline_add_history("Line 1");
readline_add_history("Line 2");
readline_add_history("Line 3");
  
// Retrieve the command line history
$history = readline_list_history();
  
// Print the command line history in reverse order
for ($i = count($history) - 1; $i >= 0; $i--) {
    echo "[$i] {$history[$i]}" . PHP_EOL;
}
?>


Output

[2] Line 3
[1] Line 2
[0] Line 1

Program 3: The following program demonstrates the readline_add_history() Function.

PHP




<?php
readline_clear_history();
  
// Add lines to command line history using a loop
for ($i = 1; $i <= 5; $i++) {
    $line = "Line $i";
    readline_add_history($line);
}
  
// Retrieve the command line history
$history = readline_list_history();
  
// Print the command line history
foreach ($history as $index => $line) {
    echo "[$index] $line" . PHP_EOL;
}
?>


Output

[0] Line 1
[1] Line 2
[2] Line 3
[3] Line 4
[4] Line 5

Reference: https://www.php.net/manual/en/function.readline-add-history.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads