Don Alexander Eckford's code for Greetings
if / elseif / switch and ternary Examples
Hour is: 3
Hour is: 3
<?php
// Include header file (likely containing HTML structure and other common elements)
include('includes/header.php');
// Enable all error reporting for debugging purposes
error_reporting(E_ALL);
// Set the time zone to America/Detroit (ensures date and time functions are
// consistent with this timezone)
date_default_timezone_set("America/Detroit");
// Output a heading for the page
echo("<h1>Don Alexander Eckford's code for Greetings</h1>");
// Output a subheading to describe what the following examples demonstrate
echo('<h2>if / elseif / switch and ternary Examples</h2>');
// Get the current hour in 24-hour format (without leading zeros), e.g., 14 for 2 PM
$hour = date('G');
// Output the current hour for reference
echo("<p>Hour is: $hour</p>");
//================ if statements ================
// If hour is between 0 and 11 (inclusive), it's morning
if ($hour >= 0 && $hour < 12)
{
echo('<H3>Good Morning!</h3>');
}
// If hour is between 12 and 17 (inclusive), it's afternoon
if ($hour >= 12 && $hour < 18)
{
echo('<H3>Good Afternoon</h3>');
}
// If hour is between 18 and 21 (inclusive), it's evening
if ($hour >= 18 && $hour < 22)
{
echo('<H3>Good Evening</h3>');
}
// If hour is between 22 and 24 (inclusive), it's night
if ($hour >= 22 && $hour <= 24)
{
echo('<H3>Good Night</h3>');
}
//=============== if-elseif-else ================
// Simplified structure: only one block is executed depending on the time
if ($hour >= 0 && $hour < 12)
{
echo('<H3>Good Morning!</h3>');
}
elseif ($hour >= 12 && $hour < 18)
{
echo('<H3>Good Afternoon</h3>');
}
elseif ($hour >= 18 && $hour < 22)
{
echo('<H3>Good Evening</h3>');
}
else
{
echo('<H3>Good Night</h3>');
}
//================ switch case ================
// Switch statement with conditions using boolean logic
switch (true) // 'true' allows for range comparisons in the case conditions
{
case ($hour >= 0 && $hour < 12):
echo('<H3>Good Morning!</h3>');
break;
case ($hour >= 12 && $hour < 18):
echo('<H3>Good Afternoon</h3>');
break;
case ($hour >= 18 && $hour < 22):
echo('<H3>Good Evening</h3>');
break;
case ($hour >= 22 && $hour <= 24):
echo('<H3>Good Night</h3>');
break;
}
//================ Simple if/else ================
// Output a heading
echo('<H3>Simple IF/ELSE</h3>');
// Simple if/else statement to set AM/PM based on the current time
if ($hour < 12)
{
$amPM = "AM";
}
else
{
$amPM = "PM";
}
// Display whether it's AM or PM
echo($amPM);
//================ Ternary operator ================
// Ternary operator: shorter version of if/else
// The condition checks if it's before 12 PM, setting AM or PM accordingly
echo('<H3>Ternary example</H3>');
$amPM = ($hour < 12) ? "AM" : "PM";
echo($amPM);
// Include footer file (likely containing closing HTML tags or common footer elements)
include('includes/footer.php');
?>