'Reading input in php from terminal

I want to read the following input in php which is entered in termial

3
5  
1 4 0 2 5  
2 0 5 1 4  
4  
1 1 7 2
1 13 2 1 
3
3 1 7
2 5 4 

Where:

  • The first line of input consists of an integer T which is the number of test cases.
  • The first line of each test case contains an integer n which indicates the size of both arrays.
  • The second and third line of each test case contains n space separated integers which are the elements of the first and second arrays respectively.

I am new to PHP, can anybody explain me the code logic of reading the input?

I don't want to store the input in a file and read it from there.

Any help would be appreciable, Thank you.

php


Solution 1:[1]

function read_from_console ($prompt = '') {
    if ( function_exists('readline') ) { 
        $line = trim(readline($prompt));
        if (!empty($line)) {
            readline_add_history($line);
        }
    } else {
        echo $prompt;
        $line = trim(fgets(STDIN));
    }
    return $line;
}

$values = preg_split('/\s+/', trim(read_from_console()));

Solution 2:[2]

To retrieve the input passed to the script via terminal, you can use the $argv variable.

For example, if you write in the terminal:

php -q /path/script.php one two three

The var_dump($argv); command will show:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "one"
  [2]=>
  string(4) "two"
  [3]=>
  string(4) "three"
}

So, to get the first you can simple write:

$first = $argv[1]; // it will be one 

Solution 3:[3]

echo 'Do you want Refresh! Go back [CTR+C or press any key]' .PHP_EOL .'Generating for new token [Y/N] ';

flush(); if ( trim( fgets( STDIN ) ) !== 'y' ) exit;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user2342558
Solution 3 Mudassar Ali Chouhan