16

I use gets to get an user input in Ruby.

# in 0015.rb
input_num = gets.to_i
p "Your input number is #{input_num}."

And I use it in a terminal.

➜  rubytest: ruby 0015.rb
24
"Your input number is 24."    

Can I do like this in PHP with terminal?

3 Answers 3

20

I think you are looking for the readline function

$number = readline("Enter a number: ");
echo 'You picked the number: '.$number;

http://www.php.net/manual/en/function.readline.php

Sign up to request clarification or add additional context in comments.

Comments

6

If you don't have readline installed, -or- you're writing a library, you should do this:

if (!function_exists('readline')) {
    function readline($question)
    {
        $fh = fopen('php://stdin', 'r');
        echo $question;
        $userInput = trim(fgets($fh));
        fclose($fh);

        return $userInput;
    }
}

$age = readline('What is your age? ');
echo "You are $age years old.\n";

Comments

0

You can use readline function. But if you search for array input then you have to also use explode function. See given example for get array input,

<?php 
    //input 1 6 5
    $a = explode(' ', readline()); //read array
    for($i=0;$i<sizeof($a);$i++)
    {
       echo $a[$i]." ";
    }

?> 
Output:
1 6 5

Using fscanf() function works same as the fscanf() function in C. We can read 2 integers from Keyboard(STDIN) as below:

This is defferent from the previous method

<?php 
  
// Input 1 5 
fscanf(STDIN, "%d %d", $a, $b); 
   
// Output 
// The sum of 1 and 5 is 6 
echo "The sum of " . $a . " and "
    . $b . " is " . ($a + $b); 
?> 


Output:
The sum of 1 and 5 is 6

For more example Link

1 Comment

You use explode function to convert a string into an array, the same way you can use implode function to convert array to string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.