Reading input in php from terminal



PHP Snippet 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()));

PHP Snippet 2:

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

PHP Snippet 3:

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

PHP Snippet 4:

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