使用php检查输入是否与数组中当前显示的项匹配

时间:2015-06-03 08:37:16

标签: php arrays search input

我有一个texfield $input和一个包含字符串$word的数组。我正在改组数组并显示用户必须匹配的$words数组中的混洗字符串。

如果改组(洗牌后的字符串也是当前显示的字符串)字符串为hello,则用户必须输入hello,然后显示“正确!”消息。或wrong!(如果不匹配100%)。

那么,我如何简单地检查用户输入是否等于$words数组中当前显示的字符串?我已经搜索了很多,但找不到任何东西。

当用户键入相应的单词时,会显示数组中的新“随机”单词,并且必须正确键入,如图所示。程序继续这样。

我试过这个:

<form method = "post" action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
            <input type = "text" name = "inputfield" id = "inputfield"><br>
            <input type = "submit" name = "submit" value = "TJEK SPELLING" id = "spelling"><br>
        </form>

$word = array("hello", "how", "are", "you", "great", "fine");
shuffle($word);

//The word that has to be matched is shown
echo reset($word);

if (isset($_POST['submit'])) {
            $input = $_POST['inputfield'];
            echo "You typed : <b> $input </b>";
            echo "<br>That was : ";

            if (in_array($input, $word)) {
                echo "<b>Correct!</b>";
            } else{
                echo "<b>Wrong</b>";
            }
        }

使用这段代码我会检查它是否在数组内部,我知道,但这是我最接近的赌注。

以下是我的迷你程序的截图:

enter image description here

任何帮助表示赞赏。 提前谢谢!

2 个答案:

答案 0 :(得分:2)

这就像分配你需要与变量匹配的单词然后进行比较一样简单:

<?php

$word = array("hello", "how", "are", "you", "great", "fine");
shuffle($word);

//The word that has to be matched is shown
$toMatch = reset($word);

if (isset($_POST['submit'])) {
    $input = $_POST['inputfield'];
    echo "You typed : <b> $input </b>";
    echo "<br>That was : ";

    if ($input === $toMatch) {
        echo "<b>Correct!</b>";
    } else{
        echo "<b>Wrong</b>";
    }
}

答案 1 :(得分:1)

如果我理解你所追求的是什么,我认为这就是你要找的东西:

<?php

if (isset($_POST['inputField']) && isset($_POST['shownWord'])) 
{
    $input = $_POST['inputField'];
    echo "You typed : <b> $input </b>";
    echo "<br>That was : ";

    if ($input === $_POST['shownWord']) {
        echo "<b>Correct!</b>";
    } else{
        echo "<b>Wrong</b>";
    }
}

$word = array("hello", "how", "are", "you", "great", "fine");
shuffle($word);
$toMatch = reset($word);
?>
<p>Enter this word: <?php echo $toMatch; ?></p>
<form name ="form" method = "POST">
    <input type="hidden" name="shownWord" value="<?php echo $toMatch; ?>" />
    <input type="text" name = "inputField" >
    <input type="submit" value="Submit">
</form>

根据您的需要,最好将随机单词保存到session,然后从那里检查匹配的单词。 E.g:

$_SESSION['shownWord'] = $toMatch;

并将if语句更改为:

if ($input === $_SESSION['shownWord']) { }