问题描述:

I'm trying to write a simple PHP script that acts like a set of flash cards. I want to have the script prompt me (via a command prompt) with a question and then once I'm ready then I hit Enter and it shows me the answer. Then I hit Enter and it shows me the next question and so on.

I've written the below script but when I press Enter the first time it goes all the way through the array and then finishes all at once. I want to have it pause for input in between each question and answer.

$questionsandanswers = array(

"What is 1 plus 1?",

"2",

"What is 2 plus 2?",

"4",

);

foreach ($questionsandanswers as $qa) {

echo $qa . "\n";

$handle = fopen ("php://stdin","r");

$line = fgets($handle);

if ($line) {

echo $qa . "\n";

fclose($handle);

}

}

网友答案:

You could launch PHP with the -a option to get it in an interactive shell. Then, format your question/answer like key => value in the array to be able to check if the input answer is good or not. Finally open the php://stdin outside of the loop.

i.e. :

user$ php -a
Interactive mode enabled

php > $handle = fopen("php://stdin", 'r');
php > $questionsandanswers = array(
php (     "What is 1 plus 1?" => 2,
php (     "What is 2 plus 2?" => 4,
php (     "What is... your favorite color?" => "Blue. Oh no... Red !"
php ( );
php > foreach ($questionsandanswers as $key => $value) {
php {     echo $key . "\n";
php {     $answer = fgets($handle);
php {     if ($answer == $value) {
php {         echo "Correct !\n";
php {     } else {
php {         echo "Wrong...\n";
php {     }
php { }
What is 1 plus 1?
2
Correct !
What is 2 plus 2?
4
Correct !
What is... your favorite color?
Green
Wrong...

Have fun ! = )

EDIT

You could also write the script in a file (Q_A_script.php) :

<?php

$handle = fopen("php://stdin", 'r');

$questionsandanswers = array(
    "What is 1 plus 1?" => 2,
    "What is 2 plus 2?" => 4,
    "What is... your favorite color?" => "Blue. Oh no... Red !"
);

foreach ($questionsandanswers as $key => $value) {
    echo $key . "\n";
    $answer = fgets($handle);
    if ($answer == $value) {
        echo "Correct !\n";
    } else {
        echo "Wrong...\n";
    }
}

fclose($handle);

?>

and launch it like any other php script from command line :

php ./Q_A_script.php

相关阅读:
Top