Follow:  Follow PHPExercises on Twitter  Follow us on Facebook

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.

 

Comments

Is this not better??

$date=getdate(date("U"));

if($date[month]=="August")echo "Its August, so its really hot.<br/>";
else echo "Not August, so at least not in the peak of the heat.<br/>";

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'.

couldn't you just use

  1. $date = date('F');

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 and it works fine.


<?php

date_default_timezone_set('Australia/Sydney');

$date = getdate();


if($date[month] == "August")
{
	echo "It's August, so it's really hot";
}
else
{
	echo "Not August, so at least not in the peak of heat";
}

?>


$today = getdate();
if (in_array("August", $today)){
	echo 'its august';
	} else {
	echo 'its not august';
	}

My compact and modular approach using a variable for the month and a ternary operation.

$month = 'August';

$is_month = "It's ".$month.", so it's really hot.";
$not_month = "Not ".$month.", so at least not in the peak of the heat.";

echo (date('F') === $month) ? $is_month : $not_month;

  1. $month = strftime( '%B' );
  2. if ( $month == "August" ) {
  3. 	echo "It`s August, so it`s really hot.";
  4. } else {
  5. 	echo "Not August, so at least not in the peak of the heat.";
  6. }