PHP Control Structures Ex. #1: If-Else Statement
In this PHP exercise, you will use a conditional statement to determine what gets printed to the browser. Write a script that gets the current month and prints one of the following responses, depending on whether it's August or not:
It's August, so it's really hot.
Not August, so at least not in the peak of the heat.
Hint: the function to get the current month is 'date('F', time())' for the month's full name.
 
 
Here's the script:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>If-Else Statement</title>
</head>
<body>
<h2>If-Else Statement</h2>
<?php
$currMonth=date('F', time());
if ($currMonth == 'August'){
echo "<p>It's August, so it's really hot.</p>";
}else{
echo "<p>Not August, so at least not in the peak of the heat.</p>";
}
?>
</body>
</html>
See the output of the script in a separate window here. You can also view the output's HTML source from the new window, if you need to check that.
To open a PHP code editor in a new tab, click here.
Comments
alternate method
Is this not better??
A good alternative
Your code is an good alternate way to solve this puzzle. You could simply use getdate(), since without arguments, it defaults to the current time (and is essentially the same as time()). Also, we get an undefined constant error from your code as written, since you did not include quotes around 'month'.
different date
couldn't you just use
without having to specify a time()? or is it just good practice to include time when calling a date?
I used the same line of code
I used the same line of code and it works fine.
using getdate() associative array
works fine
My compact and modular
My compact and modular approach using a variable for the month and a ternary operation.
$month = strftime( '%B' );
}