0

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.

user2342558
  • 5,567
  • 5
  • 33
  • 54
Gousia
  • 53
  • 14
  • 1
    You may want to check the [Input/output streams](http://php.net/manual/en/features.commandline.io-streams.php) chapter. See also [Reading line by line from STDIN](https://stackoverflow.com/questions/11968244/reading-line-by-line-from-stdin). – Álvaro González Jan 16 '18 at 09:54

3 Answers3

1

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 
user2342558
  • 5,567
  • 5
  • 33
  • 54
0
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()));
jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
  • What is $prompt? – Gousia Jan 16 '18 at 10:07
  • The text you want to show to the user as indication of what s/he has to enter. It can be an empty string. I'm going to edit... – jotaelesalinas Jan 16 '18 at 10:08
  • It is working for reading lines, but how can i store the space seperated values in a line as an array? – Gousia Jan 16 '18 at 10:21
  • I edited the answer. Use `explode()` or, better, `preg_split()`. `explode` splits by a string, so if you split by a single space `' '` and you have several spaces between two values you will get empty items. `preg_split` splits by a regular string, which is more complicated but much more powerful. In this case, we split by any succession of one or more whitespace characters (space or tab in this case). – jotaelesalinas Jan 16 '18 at 10:55
-2

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;