if-else-php-scipt,它以全名获取当前月份



我试图解决今天课堂上给出的一个关于php编码的基本if-else语句的问答问题。

问题如下:

编写一个获取当前月份的脚本,并打印以下回应,取决于是否是八月:

现在是八月,所以真的很热
不是八月,所以至少不是在最热的时候。

问题中给出的提示:获取当前月份的函数是"date('F', time())"表示月份的全名。

好的。这就是我设法写的:

<?php
  $month=date("F");
  if ($month="F") {
    echo "It's August, so it's really hot.";
  }
  else {
    echo "Not August, so at least not in the peak of the heat.";
  }
?> 

我确信我在约会活动中做错了。我很困惑。我不知道如何使用问题中的提示date('F', time())。伸出援手,有人吗?

应该是:

<?php
  $month = date('F', time());
  if ($month == 'August')
  {
    echo 'It's August, so it's really hot.';
  }
  else
  {
    echo 'Not August, so at least not in the peak of the heat.';
  }
?> 

因为'date('F', time())'会返回月份的全名。

date("F");的结果是一个单词。相反,如果数字是8,则获取要求解的数字。

   <?php
      $month = date("n"); // Get the number of the month, 1-12
      if ($month == 8) { // 8 is august
        echo "It's August, so it's really hot.";
      } else {
        echo "Not August, so at least not in the peak of the heat.";
      }
    ?> 

或者如果你更喜欢使用字符串

   <?php
      $month = date("F"); // Get name of the month
      if ($month == "August") { // If the given month is "august"
        echo "It's August, so it's really hot.";
      } else {
        echo "Not August, so at least not in the peak of the heat.";
      }
    ?> 

太想出答案了:

首先,如果要检查变量是否等于某个值,则在if语句中需要两个等号。

其次,date("F")返回当前月份的字符串"January - December"。您的代码所说的是,如果变量$month是字符串"F",那么执行一些操作。但变量$month返回一个月的字符串,目前是四月,永远不会是"F"。

<?php
  $month=date('M');
  if ($month=="Aug") {
    echo "It's August, so it's really hot.";
  }
  else {
    echo "Not August, so at least not in the peak of the heat.";
  }
?> 

最新更新