PHP语法错误 - 使用elseif

时间:2017-12-06 09:47:11

标签: php html

这是我编写的代码,但它无效。它假设向用户询问一个奇数并检查它是否正确。

代码:     

$guess = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)){
        if ($guess/2 %0){
                echo "the number you are guessing is not odd";
        }elseif{

         ($guess<$rand)
                echo "Your Guess is Smaller than the secret number";
        }elseif{
                ($guess>$rand)
                         echo "Your Guess is bigger than the secret number";
        }else{
                          ($guess==$rand)
        echo "you guessed currectly. now try anouthe number!";}





else
        header("Location: index.php");
                exit();}

?>

2 个答案:

答案 0 :(得分:3)

你能试试吗?

您放置了&#39;()&#39;在你的elseif错了。

<?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit))
{
    if($guess / 2 % 0)
    {
        echo "the number you are guessing is not odd";
    }
    elseif($guess < $rand)
    {
        echo "Your Guess is Smaller than the secret number";
    }
    elseif($guess > $rand)
    {
        echo "Your Guess is bigger than the secret number";
    }
    elseif($guess == $rand)
    {
        echo "you guessed currectly. now try anouthe number!";
    }
}
else
{
    header("Location: index.php");
    exit();
}

?>

我尚未测试此代码,因此我需要您的反馈。 修改:您已确认此操作有效。

我想向您提供有关elseif的手册: http://php.net/manual/en/control-structures.elseif.php

请考虑更简单/更清晰的编码。就个人而言,我喜欢使用&#39;:&#39;而不是&#39; {}&#39;,当您使用与HTML混合的PHP时,代码更少,更容易阅读:

<?php
$rand = rand(1, 99);

$guess  = $_POST['guess'];
$submit = $_POST['submit'];

if(isset($submit)):
    if($guess / 2 % 0):
        echo "the number you are guessing is not odd";
    elseif($guess < $rand):
        echo "Your Guess is Smaller than the secret number";
    elseif($guess > $rand):
        echo "Your Guess is bigger than the secret number";
    elseif($guess == $rand):
        echo "you guessed currectly. now try anouthe number!";
else:
    header("Location: index.php");
    exit();
endif;
?>

不要忘记查看$_POST数据。

同样适用于array,但这是旁注:

$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new

答案 1 :(得分:2)

这不是php中if-else构造的正确语法。

elseif部分需要在它之后(在开始大括号之前)有一个条件,而else根本不期待一个条件。

if ($guess/2 %0){
        echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
    // ....
} else {
    echo "you guessed currectly. now try anouthe number!";
}

当然,在你的其他人之前,你必须确保ifelseif匹配所有&#34;错误&#34;例。